Angular: Issue encountered while attempting to differentiate an '[object Object]'. Arrays and iterables are the only permissible types for this operation


I encountered the following error message while attempting to retrieve updated data:

Error trying to diff '[object Object]'. Only arrays and iterables are allowed

Snippet of Get Code:

allDatas
  allData(data) {
    this.allDatas = data
  }

Update Code I Wrote:

updateTodo(currentTodo){  
       // console.log(currentTodo)
        this._todo.updateTask(currentTodo).subscribe(
          data=>{console.log(data);this.allData(data)},
          error=>console.log(error)
        )
  }

This Request Originates From Service.ts

updateTask(todo:TodoModel):Observable<TodoModel>{
    return this._http.put<TodoModel>('http://127.0.0.1:3000/todo/updateTodo/'+todo.id,todo,headerOption)
  }

After thorough debugging with console.log, pinpointed the line where the error occurs:

updateTodo(currentTodo){  
           // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{console.log(data);this.allData(data)}, //Error Comes from this line----------
              error=>console.log(error)
            )
      }

When I adjust the update code to simply data=>console.log(data), the error disappears. However, using

data=>{console.log(data);this.allData(data)}
triggers the error:

https://i.sstatic.net/iAYDC.jpg

HTML Snippet Where Data is Bound:

<tbody *ngFor="let t of allDatas;let i= index">
                <tr class="table-success" *ngIf="t && t.complited">
                    <td>{{t.task}}</td>
                    <td>{{t.date.year+"-"+t.date.month+"-"+t.date.day}}</td>
                    <td> {{t.complited}}</td>
                    <td>
                        <i class="fa fa-times-circle btn idelete" style="font-size:25px;" (click)="putTrue(t)"></i>
                        <i class="fa fa-edit btn iedit" style="font-size:25px;color:rgb(31, 12, 12)" (click)="editTodo(t)"></i>
                        <i class="fa fa-trash-o btn idelete" style="font-size:25px;" (click)="deleteTask(t.id)"></i>
                    </td>
                </tr>
                <tr class="table-danger" *ngIf="t && !t.complited">
                    <td>{{t.task}}</td>
                    <td>{{t.date.year+"-"+t.date.month+"-"+t.date.day}}</td>
                    <td> {{t.complited}}</td>
                    <td>
                        <i class="fa fa-check-circle btn idone" style="font-size:25px;" (click)="putTrue(t)"></i>
                        <i class="fa fa-edit btn iedit" style="font-size:25px;color:rgb(31, 12, 12)" (click)="editTodo(t)"></i>
                        <i class="fa fa-trash-o btn idelete" style="font-size:25px;" (click)="deleteTask(t.id)"></i>
                    </td>
                </tr>
            </tbody>

AllDatas is an array:

https://i.sstatic.net/Utcux.jpg

JSON Data for Operations:

[{"id":29,"task":"random 5","date":{"year":2020,"month":5,"day":9},"category":"genral","complited":false},null,{"id":31,"task":"task 32","date":{"year":2020,"month":5,"day":31},"category":"genral","complited":false}]

In short, encountering an error specifically when updating a task and retrieving the updated task. Same method used for other operations yielding perfect results.

Answer №1

Based on my interpretation of the provided code, it seems that the error is occurring because you are attempting to assign an object to an array within the allData method.

When subscribing to the PUT request, you are receiving an object instead of an array.

To resolve this issue, your allData method should be structured as follows:

allData(data) {
    this.allDatas.push(data);
}

Answer №2

Make sure to initialize allDatas: this.allDatas=[]

updateTodo(currentTodo){  
          // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{
               this.allDatas=[]
               console.log(data);
               this.allDatas.push(data)
}

            )
      }

However, a more effective solution would be to modify the return type of your API to an array []

Answer №3

This issue seems to be connected to the *ngFor loop in your HTML file. It is indicating that the variable allDatas is not being recognized as an array.

To address this, check the data type of allDatas using the "typeof" operator to confirm that it is indeed an array.

UPDATE
Upon reviewing the second image, it appears that allDatas is actually an array.
I recommend validating this array using an online JSON validator tool, which can be found through a quick Google search.

Additionally, consider moving the *ngFor loop from within <tbody> tags to <tr> for better organization.

Best of luck with resolving this issue!

Answer №4

Give this a shot:
If you set this.allDatas = data;, the allDatas will be refreshed and 'allDatas' will be equal to 'data'.
If you use this.allDatas.push(data);, the 'data' will be newly added into the 'allDatas'

Start off by creating an array called allDatas: Array = [];

   allDatas : Array<any> = [];

updateTodo(currentTodo){  
          // console.log(currentTodo)
            this._todo.updateTask(currentTodo).subscribe(
              data=>{
               console.log(data);
               this.allDatas = data;
});
      }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to add text to a bar chart in morris.js

I have a morris.js bar graph and I want to display the count on top of each bar. After checking the morris.js bar documentation, I couldn't find a solution for it. When hovering over the bars, it should show the value, but I specifically need to show ...

Error encountered during production build of Angular 6 Universal with server-side rendering (SSR

I have recently delved into Angular 6 and managed to nearly complete my app. However, I am encountering some struggles with server-side rendering (SSR). Following a tutorial on SSR at this link, I tried running the command npm run build:ssr && npm ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

Changing the background color of the canvas using Javascript

I want to create a rect on a canvas with a slightly transparent background, but I don't want the drawn rect to have any background. Here is an example of what I'm looking for: https://i.stack.imgur.com/axtcE.png The code I am using is as follo ...

Executing an Angular 4 script using a scheduled CRON job

We are currently facing a challenge with our Angular-built APP for Android phones. The logic has become quite intricate and we have decided to transfer it to our server, where it can be executed as a CRON job every hour instead of within the Phone APP it ...

Using AJAX to transform octet-stream into typed array (Float64Array)

I can't seem to figure out where I'm going wrong here. My attempt involves converting a binary stream obtained from an AJAX request into an array of doubles using JavaScript. Here is some of my code: The PHP script on my server returns an octet-s ...

Is it advisable to use Angular $resource JSON Callback if it's not functioning correctly?

I am in the process of creating a resource to send data to my controller for an existing API that I need to connect with. Unfortunately, I do not have the ability to make any changes on the backend. Current state of my Resource factory: 'use strict& ...

Is there a way to prevent this JavaScript code from deleting the initial row of my table?

Looking at the code provided, it's evident that creating and deleting new rows is a straightforward process. However, there seems to be an issue where the default/origin/first row (A-T) gets deleted along with the rest of the rows. The main requiremen ...

Custom Native Scrollbar

Currently, there are jQuery plugins available that can transform a system's default scroll bar to resemble the iOS scroll bar. Examples of such plugins include . However, the example code for these plugins typically requires a fixed height in order to ...

Using jQuery or JavaScript to clear multiple selections in a multiselect dropdown when a button is clicked

Is there a way to clear the dropdown selections once my function saves data to local storage? You can refer to this fiddle for more details: http://jsfiddle.net/3u7Xj/139/ I already have code in place to handle other form elements: var $form = $("#formI ...

Issue in Vue.js: Struggling to compile SASS styles for an HTML element generated dynamically

I'm working with a basic Vue.js component where I'm rendering a snippet of HTML: ... <div class="sml-button" v-on:click="toggleButton()" v-html="button"></div> ... When the button is clicked, the toggleButton() function updates the ...

Using switch statement upon page loading in AngularJS

I am currently working on refactoring a switch statement that identifies specific classes upon page load into one of my controllers. Does anyone have suggestions on how I can transform this straightforward task using Angular? $('.radior').eac ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

Toggle Canvas Visibility with Radio Button

As I immerse myself in learning Javascript and Canvas, the plethora of resources available has left me feeling a bit overwhelmed. Currently, I am working on a dress customization project using Canvas. // Here is a snippet of my HTML code <input type=" ...

Unable to retrieve information from the redux store

I'm having trouble accessing a property from a Redux store while working with Angular. Within the IApp interface, there are two properties: one is an interface and the other is a number. interface AppStoreInterface { layoutInterface: LayoutInterfa ...

NavLinkButton - add style when active or selected

I'm working with a list of NavLinks: const users = Array.from(Array(5).keys()).map((key) => ({ id: key, name: `User ${key}`, })); <List> {users.map((user) => { return ( <ListItem disablePadding key={user.id}> ...

How to Create a Flexible Angular Array Input Component

I have been working on developing reusable form input components using Angular's reactive forms. However, I am currently encountering challenges with my FormArray input component. To overcome some issues, I had to resort to using double-type casting ...

Sending data to the makeStyle function in TypeScript

How can I set the style of backgroundImage in my React component based on the value of post.mainImage? Here is the code snippet: import React from 'react'; import { Post } from '../interfaces'; import { makeStyles, createStyles, Theme ...

Is it more advantageous in Vue to pre-process and save data directly to the data property, or to utilize computed properties?

I am interested in hearing diverse perspectives on this topic. When working with Vue (and possibly other frameworks), is it more beneficial to prepare non-reactive data through a method and store it in the data for use in the template, or is it preferable ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...