0

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

3 Answers3

2

try changing the for loop with this


    for(let i = 0 ; i < result.Products.length ;i++)
    {
       console.log( result.Products[thii].productid +" "+result.Products[i].name)
       this.name = result.Products[i].name
    }

for html file:

<ul> 
  <li *ngFor="let i of result.Products"> 
    {{i.name}} 
  </li> 
</ul>
1

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> 
zainhassan
  • 1,684
  • 6
  • 12
0

I would use forEach().

return this.httpClient.get(this.apiURL).subscribe((result: any)=>{
     if(result.status == "false" )
      console.log("result",result.status)
    else 
    {
      this.name = result.Products[0].name;
      result.Products.forEach((fruits, index) => {

        console.log( result.Products[index].productid +" " +result.Products[index].name )

      });
      
    }

 }

Check this post for more info about forEach() with index: TypeScript for ... of with index / key?

matsch
  • 281
  • 4
  • 14