Encountering a Angular 12 Observable<Object[]> Error while attempting to execute a GET request

I've been grappling with this error I encountered while working on Angular 12.

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays.

This is the code for my service:

import { HttpClient } from '@angular/common/http';
import { Catalog } from './../Models/Catalog';
import { Observable } from 'rxjs';

const baseUrl = 'http://localhost:8080/'

@Injectable ({
 providedIn: 'root'
})

export class CatalogService {

 constructor(private http: HttpClient) { }

 getAll(): Observable<Catalog[]> {
   console.log(this.http.get<Catalog[]>(baseUrl));
   return this.http.get<Catalog[]>(baseUrl);
 }

Here's the component code:

import { Router } from '@angular/router';
import { CatalogService } from './../../Services/catalog.service';
import { Catalog } from "./../../Models/Catalog";
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-catalog',
  templateUrl: './catalog.component.html',
  styleUrls: ['./catalog.component.scss']
})

export class CatalogComponent implements OnInit {

  catalog?: Catalog[];
  currentCatalog: Catalog = {};
  currentIndex = -1;
  constructor(private catalogService: CatalogService) { }

  ngOnInit(): void {
    this.retrieveCatalog();
  }

  retrieveCatalog(): void {
    this.catalogService.getAll()
      .subscribe(
        data => {
          this.catalog = data;
          console.log(data);
        },
        error => {
          console.log(error);
        });
  } 

Below is the HTML part:

<div class="containter">
  <table class="table table-bordered">
    <thead>
      <tr>
        <th scope="col">Id</th>
        <th scope="col">Model</th>
        <th scope="col">Price</th>
        <th scope="col">Specification</th>
        <th scope="col">Image</th>
      </tr>
    </thead>
    <tbody>
      <tr *ngFor="let catalog of catalog; let i = index">
        <th scope="row">{{catalog.id}}</th>
        <td>{{catalog.model}}</td>
        <td>{{catalog.price}}</td>
        <td>{{catalog.specification}}</td>
        <td>{{catalog.image}}</td>
      </tr>
    </tbody>
  </table>
</div>

I was following a tutorial on using serializable with the MEAN stack:

However, upon loading the page, I encountered the mentioned error.

My queries are:

Why is this happening? (I'm fairly new to Angular)

Is this the correct way to return an array with Observables? "this.http.get<Catalog[]>(baseUrl);"

EDIT: Output for the method in the service class:

Observable
operator: MapOperator {thisArg: undefined, project: ƒ}
source: Observable
operator: FilterOperator
predicate: (event) => event instanceof HttpResponse
thisArg: undefined
[[Prototype]]: Object
call: ƒ call(subscriber, source)
constructor: class FilterOperator
[[Prototype]]: Object
source: Observable
operator: MergeMapOperator {concurrent: 1, project: ƒ}
source: Observable {_isScalar: false, _subscribe: ƒ}
_isScalar: false
[[Prototype]]: Object
_isScalar: false
[[Prototype]]: Object
_isScalar: false
[[Prototype]]: Object

Edit: Output from the subscribe method

Subscriber {closed: false, _parentOrParents: null, _subscriptions: Array(1), syncErrorValue: null, syncErrorThrown: false, …}
closed: true
destination: SafeSubscriber
closed: true
destination: {closed: true, next: ƒ, error: ƒ, complete: ƒ}
isStopped: true
syncErrorThrowable: false
syncErrorThrown: false
syncErrorValue: null
_complete: undefined
_context: null
_error: error => { console.log(error); }
_next: data => {…}
_parentOrParents: null
_parentSubscriber: null
_subscriptions: null
[[Prototype]]: Subscriber
isStopped: true
syncErrorThrowable: true
syncErrorThrown: false
syncErrorValue: null
_parentOrParents: null
_subscriptions: null
[[Prototype]]: Subscription
complete: ƒ complete()
constructor: class Subscriber
error: ƒ error(err)
next: ƒ next(value)
unsubscribe: ƒ unsubscribe()
_complete: ƒ _complete()
_error: ƒ _error(err)
_next: ƒ _next(value)
_unsubscribeAndRecycle: ƒ _unsubscribeAndRecycle()
Symbol(rxSubscriber): ƒ [_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_2__.rxSubscriber]()
[[Prototype]]: Object

Thank you!

Answer №1

Let's simplify things to streamline the process. To enhance performance, my suggestion is to utilize the async pipe. Allow me to demonstrate.

In your component.ts file, there's no need for a retrieveCatalogo method. Instead, we will keep the observable and use it directly in the template with the async pipe.

Here is the component setup:

import { Router } from '@angular/router';
import { CatalogoService } from './../../Services/catalogo.service';
import { Catalogo } from "./../../Models/Catalogo";
import { FormGroup, FormBuilder } from '@angular/forms';

@Component({
  selector: 'app-catalogo',
  templateUrl: './catalogo.component.html',
  styleUrls: ['./catalogo.component.scss']
})

export class CatalogoComponent implements OnInit {
  
  // Following the convention, we use the $ sign at the end of variable names for storing observables and subscriptions.
  catalogos$!: Observable<Catalogo[]>;
  currentCatalogo: Catalogo = {};
  currentIndex = -1;
  constructor(private catalogoService: CatalogoService) { }

  ngOnInit(): void {
    // We fetch the data from the service and store it as an observable
    this.catalogos$ = this.catalogoService.getAll();
  }

Next, in your component template, remember to use the async pipe

...
    <tbody *ngIf="catalogos$ | async as catalogos">
      <tr *ngFor="let catalogo of catalogos">
        <th scope="row">{{catalogo.id}}</th>
        <td>{{catalogo.modelo}}</td>
        <td>{{catalogo.precio}}</td>
        <td>{{catalogo.especificacion}}</td>
        <td>{{catalogo.imagen}}</td>
      </tr>
    </tbody>
...

The async pipe takes care of unsubscribing automatically https://angular.io/api/common/AsyncPipe

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

Best practices for transferring objects between components while navigating routes in Angular

I need some advice on handling a specific component in my project. Here is the code snippet: <div class="animal"> <a routerLink="/animal/{{animal.id}}"> <div> ... </div> </a> </div> This component receives ...

Is there a way to turn off the information log from the Express server in node.js?

I am currently working on setting up a basic express server using node.js on replit.com, and it's running smoothly so far. However, every time I start the application, I encounter some really annoying console output: Server { insecureHTTPParser: und ...

Angulating Service Testing

I am encountering an issue that I'm not sure how to resolve because I am inexperienced when it comes to testing. Currently, I am testing a service that includes the following code: import { Injectable } from '@angular/core'; import { Endpo ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Refresh child route independently without relying on data from parent route

I am currently facing an issue with my component 'panel' that has two child routes: dashboard and holidays. Both of these child routes are supposed to receive data from the parent component service in their ngOnInit. While everything is working ...

Ways to resolve the issue of the missing property 'ganttContainer' on the 'Gantt' type

I encountered an issue while trying to utilize the Gantt chart feature from the Dhtmlx library in TypeScript. The problem seems to stem from an error during the initialization of gantt. How can I go about resolving this? Below is the relevant code snippet: ...

The properties are absent in Angular Service - Observable

I recently started learning angular and I'm struggling to make this HTTP get request work. I have been looking at various examples of get requests for arrays and attempted to modify one for a single object (a user profile) but without success. The err ...

Acquire the property that broadens the interface

I'm currently working on a TypeScript function that aims to retrieve a property from an object with the condition that the returned property must extend a certain HasID interface. I envision being able to utilize it in this manner: let obj = { foo ...

Missing "this" after initialization? (typescript/node/express)

I am currently working on creating a basic http application using node-express. One issue I encountered is that when setting up routes, the constructor of the MyRouter class has access to this, but it seems to be lost within the getRoutes() function. cla ...

Creating dynamic form groups in Angular 4

I am currently working on a dynamic form group and I am facing a particular challenge. https://i.sstatic.net/m20IO.png Whenever I click on "add more," it should add 2 dynamic fields. Here is the function I am using: onAddSurgeries(){ const control = ...

send the checkbox control's model value back to the parent control in Vue3

I've implemented a wrapper control for checkboxes that closely resembles my textbox control. This approach ensures consistent validation and design throughout the application. While I was successful in getting it to work for textboxes, I encountered s ...

Encountering a crash when trying to create a form within a subscription in Angular 2 due to the formGroup being

I have data stored in my Firebase database that I want to use in a form using FormBuilder. Although it generally works fine, I often encounter errors saying formGroup expects a FormGroup instance. Please pass one in.. What confuses me is that the error oc ...

How can you assign a strokeStyle color to a Canvas using a CSS property?

Our team is currently working on an Angular2 / Ionic 2 project where we have implemented a HTML Canvas element that allows users to draw on it. One challenge we are facing is how to set the Canvas strokeStyle property using a color provided by a CSS style. ...

The TypeScript factory class anticipates an intersection

In my code, I have a class factory called pickSomething that generates a specific type based on a key provided from a ClassMap: class A { keya = "a" as const; } class B { keyb = "b" as const; } type ClassMap = { a: A b: B } c ...

Guide on how to use window.resize subscription in an Angular service?

I have been experimenting with the WindowService in my Angular project. Here is the code I have written: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; interface WindowSize { width?: number; height? ...

Using RXJS with the 'never' subject as the specified generic type

In my current Angular project, I am using RXJS and Typescript. The code snippet below shows what I have implemented: const sub = new Subject<never>(); My understanding is that the above line implies that any subscriber defining the 'next' ...

Collaborating on user authorization within a MEAN.JS framework

Recently, I decided to dive into the world of web application development by using MEAN.js full stack solution. Using the generators within MEAN.js, I was able to effortlessly create multiple CRUD models along with all the necessary express routes. In ad ...

I am experiencing issues with my Angular2 project where not all of my component variables are being passed to the

My problem involves sending three variables to my HTML template, but it only recognizes one of them. The HTML template I am using looks like this: <div class="page-data"> <form method="post" action="api/roles/edit/{{role?.ID}}" name="{{role? ...

Encountering a MODULE_NOT_FOUND error while trying to execute "npm run build"

I have encountered an issue while trying to deploy my application on my GoDaddy server. Upon running 'npm run build,' I am receiving the following error message: PS C:\Users\trump\Documents\Rider Project\PreChiS-E---Stud ...

Combining conditions and CSS classes within the ngClass directive in Angular

Is it possible to combine a condition and a class within the same "ngClass" in Angular? [ngClass]="{cssclass1 : object.cssclass1status , object.cssclass2}" The condition (bold) and CSS class (italic) can be used together. Previously, I have implemented t ...