-1

I have this component where I am pulling data from a REST API using the HttpClient. The pulling of the data works well. I could tell because I could see the data being displayed in Console Log.

When it comes to using the data in the HTML I am stuck. I can't figure how to do so. Nothing is broken the Data just won't show.

Here is my Code

Imports in the Component

    import { Component, OnInit } from '@angular/core';
    import {MatTabsModule} from '@angular/material/tabs';
    import {MatListModule} from '@angular/material/list'; 
    import { Observable } from 'rxjs';
    import {HttpClient, HttpHeaders} from '@angular/common/http';

This is the class

    export class TestComponent implements OnInit {
    constructor(private http: HttpClient ) {
    
    this.http
    .get<any>('http://api.data_redacted_for_privacy').subscribe(data => {
    console.log(data);
    });
    }

    ngOnInit(){

    this.http
    .get<any>('http://api.data_redacted_for_privacy').subscribe(data => {
    console.log(data);
    });

    }
    }

The HTML is as follows

<div *ngFor="let data">{{data.id}}</div>

I tried adding and Observable, but i believe my implementation is wrong. Sure is not like using AngularFire.

1 Answers1

1

Assign the returned data to a class variable, then loop through it using let... of...:

export class TestComponent implements OnInit {

   allData: any = null; // or any other type you have at your disposal

   constructor(private http: HttpClient){} // you don't need to subscribe to the same endpoint (if it's the same endpoint, disregard the comment if it's not!)

   ngOnInit(){

       this.http.get<any>('http://api.data_redacted_for_privacy').subscribe(data => {
          console.log(data);
          this.allData = data;
        });
    }

}

Then in template: <div *ngFor="let data of allData">{{data.id}}</div>

Misha Mashina
  • 1,739
  • 2
  • 4
  • 10
  • I am getting an error in the console that says **Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the keyvalue pipe?** . I am assuming this is RxJs pipe. How do i fix this ? – soobnaibot May 07 '23 at 01:52
  • So it seems your data returned from the sub is not an array. Can you show the log of `data`? – Misha Mashina May 07 '23 at 05:43
  • Thanks for all your help. I finally figured it out. I changed this `this.allData = data;` into `this.allData = [data];` . The API sends a plain **.json** file. Unlike some NoSql databases. – soobnaibot May 08 '23 at 02:09