【问题标题】:how to loop through angular get request responce如何循环通过角度获取请求响应
【发布时间】:2021-07-03 02:36:08
【问题描述】:

我有一个获取请求的响应

{
    "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;,它显示最后产品名称

【问题讨论】:

    标签: angular data-binding


    【解决方案1】:

    尝试用这个改变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>
    

    【讨论】:

    • 它在 {{name}} 中显示最后一个产品,并将第一个产品打印到 result.length
    • 请将此代码放入您的 html 文件中。
      • {{i.name}}
    • 如果要显示结果的所有项目,只需使用 html 代码。甚至不需要for() 循环。
    【解决方案2】:

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

    查看此帖子以获取有关forEach()index 的更多信息:TypeScript for ... of with index / key?

    【讨论】:

    • 我的目标不在控制台中打印。我需要 html 中的这些名称,即 {{name}} 中的循环
    【解决方案3】:

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

    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> 
    

    【讨论】:

      猜你喜欢
      • 2020-03-31
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多