如何循环 angular 获取请求响应

how to loop through angular get request responce

我有一个获取请求响应

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

compoent.ts 为

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 )

    }

  }

})} 

我需要在 component.html 中显示这些名称。我试过 {{name}} 但它只显示第一个产品名称,即菠萝蜜..如果我在 for 中给出 this.name = result.Products[this.i].name;循环,它显示最后一个产品名称

尝试用这个改变 for 循环


    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
    }

对于 html 文件:

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

我会用 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 )

      });
      
    }

 }

查看此 post 以获取有关 forEach()index 的更多信息:

您需要创建一个名称数组而不是变量。

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);
        }
    })
}

那么在你HTML你可以使用

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