[Fixed] how to loop through angular get request responce

Issue

i have a get request responce as

{
    "status": "true",
    "Products": [
        {
            "productid": 1,
            "addedby": 0,
            "name": "Jackfruit",
            "slug": "jackfruit",
etc....}]}

the compoent.ts as

i = 0;
  name = "";
  
  constructor(private httpClient: HttpClient) { }


  ngOnInit() { 
    
    return this.httpClient.get(this.apiURL).subscribe((result: any)=>{
     if(result.status == "false" )
      console.log("result",result.status)
    else 
    {
      this.name = result.Products[this.i].name;
      for(this.i ;this.i < result.Products.length ;this.i++)
     {
      
        console.log( result.Products[this.i].productid +" " +result.Products[this.i].name )

    }

  }

})} 

i need to display those names in component.html..i tried {{name}} but it is showing only 1st product name i.e jackfruit.. and if i give this.name = result.Products[this.i].name; inside the for loop, it is showing last product name

Solution

You need to create an array of names not a variable.

names = [];

constructor(private httpClient: HttpClient) { }

ngOnInit() {

    return this.httpClient.get(this.apiURL).subscribe((result: any) => {
        if (result.status == "false")
            console.log("result", result.status)
        else {
            this.names = result.Products.map(p => p.name);
        }
    })
}

Then in you HTML you can use

<li *ngFor="let name of names"> 
    {{name}} 
</li> 

Leave a Reply

(*) Required, Your email will not be published