【问题标题】:Error converting json response to an array in angular 2将json响应转换为角度2中的数组时出错
【发布时间】:2018-05-31 05:55:29
【问题描述】:

我正在尝试将 json 响应转换为角度 2 中的数组。以下是我使用的代码,

.ts 文件

  response;
  resp;
  constructor(private http:Http) {
   }
   get()
   {
         this.http.get("http://localhost:3000/items")
         .map(res=>res.json())
         .subscribe(data=>this.response = JSON.stringify(data))

           this.resp = JSON.parse(this.response);
      }

component.html

 {{response}}
 <ul>
    <li *ngFor="let k of resp">{{k}}</li>
  </ul>

</div>

虽然 {{response}} 只是导致显示整个 json 内容,但我无法遍历在 resp 中检索到的响应,尽管使用了 JSON.parse()。

如何将响应转换为数组并访问各个属性?

【问题讨论】:

  • 你能给我this.response的控制台输出吗??

标签: json typescript angular2-http


【解决方案1】:

根据您的代码,我看不到您正在设置 resp 变量。

您将值存储在响应变量中并在 resp 变量上进行迭代。

应该是 (let k of response) 而不是 (let k of resp)

【讨论】:

    【解决方案2】:

    您只能使用 ngFor 迭代数组。如果您的响应是一个 json 对象,那么您不能直接使用 ngFor 对其进行迭代。为此,您需要使用管道通过 ngFor 迭代 json 对象。

    你可以创建一个管道。

    @Pipe({ name: 'keys',  pure: false })
    export class KeysPipe implements PipeTransform {
        transform(value: any, args: any[] = null): any {
            return Object.keys(value)
        }
    }
    

    在你的模块中导入这个管道并在声明中传递它。然后你可以像这样在你的 html 中使用它:

     {{response}}
     <ul>
        <li *ngFor="let k of resp | keys">{{k}}</li>
      </ul>
    
    </div>
    

    【讨论】:

      猜你喜欢
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-20
      • 2021-05-17
      • 1970-01-01
      • 2021-12-03
      • 2019-07-04
      相关资源
      最近更新 更多