An issue occurred while attempting to differentiate the '[object Object]'. Angular-11 Application only accepts arrays and iterables for this operation

When using *ngFor, I am facing an issue with fetching data from my component.ts to my component.html

Interestingly, the same method works for one class but not for another.

Let's take a look at my service class:

export class FoodListService {
  private url = environment.serverURL;

  constructor(private http: HttpClient) {
  }

  //get all products from one store
  getAllProducts(storeId: Number): Observable<FoodListModelServer[]> {
    return this.http.get<FoodListModelServer[]>(this.url + 'foodlist/' + storeId);
  }

Moving on to my component class:

export class FoodListComponent implements OnInit {

  foodlist: FoodListModelServer[] = [];
  
constructor(private foodListService: FoodListService, private router: Router, private route: ActivatedRoute) {}

ngOnInit(): void {
    
      this.foodListService.getAllProducts(this.storeId).subscribe(food => {

        this.foodlist = food;
        console.log(this.foodlist);
      });    
   }
}

And here is how it looks in my component.html:

<div class="col-md-8 col-lg-10 col-sm-6 card">
        <li *ngFor="let foodlist of foodlist">
            {{foodlist.food_name}}
            
        </li>
</div>

Regarding Console.log(this.foodlist):

Upon checking, I see an object {count: 5, stores: Array(5)}

I wonder why there is a count included in the object instead of just listing the Array?

How can I retrieve only the array without the count?

Interestingly, the code works perfectly fine in another component. Despite trying various online suggestions, I have not been able to make progress on this problem.

Answer №1

I'm curious about why the object is included with the count instead of just an Array.

  • The way the API is implemented on the backend can affect this.

Is there a way to obtain only the array?

  1. Create an interface for the response from the API and use
    this.http.get<FoodListModelServerResponse>
  2. Use RxJs map operator to extract the array -
    map(response => response.stores)
    (more information here: https://www.learnrxjs.io/learn-rxjs/operators/transformation/map)
  3. After subscribing to getAllProducts, you will receive the array.
import { map } from 'rxjs/operators';

export interface FoodListModelServerResponse {
count: number;
stores: FoodListModelServer[];
}

export class FoodListService {
  private url = environment.serverURL;

  constructor(private http: HttpClient) {
  }

  getAllProducts(storeId: Number): Observable<FoodListModelServer[]> {
    return this.http.get<FoodListModelServerResponse >(this.url + 'foodlist/' + storeId)
.pipe(map(response => response.stores));
  }

You can now implement your code using this method.

ngOnInit(): void {
    
      this.foodListService.getAllProducts(this.storeId).subscribe(food => {

        this.foodlist = food;
        console.log(this.foodlist);
      });    
   }
}

Answer №2

Utilize the RxJs pluck operator in order to extract stores from the response object. Declare a variable named foodlist as

foodlist$: Observable<FoodListModelServer[]>
so that it can be assigned to an observable.

Within the foodService, return Observable<any> like

getAllProducts(storeId: Number): Observable<any>

import { pluck} from 'rxjs/operators';
import { Observable } from 'rxjs';

export class FoodListComponent implements OnInit {

    foodlist$: Observable<FoodListModelServer[]>;
      
    constructor(private foodListService: FoodListService, private router: Router, private route: ActivatedRoute) {}

    ngOnInit(): void {
          this.foodlist$ = this.foodListService.getAllProducts(this.storeId).pipe(
            pluck('stores')
          ); 
     }
}

When working in the template, make use of the Async pipe, which will handle the subscription and unsubscription to your foodListService.getAllProducts

<div class="col-md-8 col-lg-10 col-sm-6 card">
    <li *ngFor="let foodlist of foodlist$ | async">
        {{foodlist.food_name}}
    </li>
</div>

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

What steps can be taken to enhance cleanliness and efficiency, and what are some recommended practices to adhere to?

Currently, I am in the process of developing a user authentication system on the backend. Specifically, I have implemented a POST method for registering new users. userRouter.post("/", expressAsyncHandler(async (req, res) => { try { const { na ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Developing a declaration for an unnamed function in a JavaScript file

module.exports = function (argument1, argument2) { return { myFunction } function myFunction () { ... } } What is the process for creating a TypeScript declaration file for this specific JavaScript file? ...

This function does not have the capability to save cookies

I am attempting to create and retrieve a cookie using JavaScript. Despite running the code below in Google Chrome, the cookie does not persist after page reload. Here is my code: <html> <title> Cookies </title> <b ...

Creating a stunning horizontal bar chart with the react-d3-components framework

I am currently implementing a D3 chart using the react-d3-components library. So far, I have successfully generated a vertical bar chart. However, my specific requirement is to create a horizontal bar chart. import React from 'react'; import Reac ...

Is it possible to programmatically alter dropdown values in an Ionic 2 TypeScript file?

One form has been created with dependent drop-downs and some input fields. I am aiming for it to work in two scenarios: If the session is initially null, then no data should be displayed in the form and all fields should be blank by default (which has al ...

Can someone explain the process of adding a JavaScript state variable from one React component so that it can be utilized in other components?

In my Home.js component, I handle user sign up to the API and login. After receiving the token from the authorization header in the response, I save it in the state variable 'token'. This token is crucial for accessing the API in other component ...

Verifying updates in the watchlist once data has been initialized upon mounting

When trying to edit a component, the data is loaded with mounted in the following way: mounted () { var sectionKey = this.$store.getters.getCurrentEditionKey this.table = _.clone(this.$store.getters.getDocumentAttributes[sectionKey]) this.ta ...

How can JSON data be passed to the Google Charts API?

I am currently working on a project that involves retrieving JSON data from a website and visualizing it on a live graph using the Google Charts API. Despite my efforts, I am unable to get the chart to display properly. Can someone please guide me in the r ...

Oops! Looks like node.js is throwing an error with the message "connect ECONNREFUSED"

After creating a node.js application that interacts with a locally installed MySQL database, I encountered an issue where running the app through CMD (npm start) returned the desired results, but testing it through Postman resulted in an error: connect E ...

What is the method for instructing the Typescript compiler to process JSX within .ts files?

My .ts files contain .jsx syntax, and I am looking to instruct tsc on how to compile them the way it compiles .tsx files. Is there a way to adjust the configuration of tsc to achieve this? Additionally, are there steps to configure vscode for proper synt ...

Multiple jQuery load() requests are being triggered by calling it from within the ajaxComplete() callback

I've been stuck on this issue for quite some time now. To troubleshoot, I suggest using Firebug to inspect the AJAX requests. It seems that they are multiplying with each click of the next and previous buttons, causing the page to load slowly: You ca ...

The utilization of ~ (tilde) for SCSS file imports seems to be malfunctioning in Angular 6

Having some issues with importing SCSS files in Angular6, need clarification on a couple of things: If I import my partials once in the global src/sass/styles.scss, do I still need to import them individually in all component.scss files? Is there a way t ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

In Angular, the process of duplicating an array by value within a foreach function is not

I have been attempting to duplicate an array within another array and make modifications as needed. this.question?.labels.forEach((element) => { element["options"] = [...this.question?.options]; // I've tried json.stringify() as wel ...

The URL redirect is malfunctioning and prompting an error stating "No 'Access-Control-Allow-Origin' header"

Having trouble sending an Ajax request to a Node.js server from my application and encountering the following error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the ...

Verifying One Time Password (OTP) from MSG91 URL using ReactJS

Currently, I am working on a small project that involves receiving and verifying OTPs from MSG91. While I have managed to successfully receive OTPs using MSG91, I am encountering an issue when trying to verify OTPs - specifically, I keep getting an error ...

The AngularJS framework is not effectively generating the desired table structure

EDIT 1 - Here is a Plnkr example that demonstrates the issue - http://plnkr.co/edit/qQn2K3JtSNoPXs9vI7CK?p=preview ---------------- ORIGINAL CODE AND PROBLEM ---------------- I've been using the angular datatable library (angular-datatables) to g ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

Node.js Axios Returns Bad Request with Status Code 400

I am currently facing an issue while trying to send the results of a nodejs query to an endpoint. Interestingly, I receive a successful response when using Postman with the correct parameters, but encounter errors when attempting to use axios. data: ' ...