我正在尝试将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内容,但尽管使用JSON.parse(),我还是无法迭代在resp中检索到的响应。
如何将响应转换为数组并访问各个属性?
发布于 2017-12-28 13:24:44
根据您的代码,我看不到您正在设置resp变量。
您正在响应变量中存储值,并在resp变量上进行迭代。
它应该是(让k的反应)而不是(让k的重新)。
发布于 2018-01-06 18:36:08
您只能使用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>
https://stackoverflow.com/questions/47859161
复制相似问题