我试图通过 Angular 显示 json 对象中列表中的对象,但我无法真正让它工作。
json 通过服务作为已解析的 Promise 传递:
getJson(): Promise<any> {
return Promise.resolve(this.testdata);
}
因此函数返回 [object Promise]
testdata json 字符串的结构为:
{"errorCode":"ok",
"objList":[{},{},etc.]
}
我想要的是显示一个列表(例如使用 ngFor)并可以访问 objList 中对象的属性。
我最初的想法是使用 ngFor 迭代对象列表,为此我创建了以下类
export class ExampleComponent implements OnInit {
json : {"objList": []}
constructor(
private router: Router,
public app: AppService,
public pService: pService
) {
}
ngOnInit(){
this.json = this.pService.getJson()
}
}
但这不起作用,因为我收到属性 objList
的错误类型 Promise<any>
中缺失.
我还尝试使用 KeyValue 管道使用 ngFor,但它也无法正常工作。
如果有任何帮助,我将不胜感激。
最佳答案
你能试试这个代码片段吗
ngOnInit(){
this.pService.getJson().
then(response => {
this.json = response;
})
}
关于javascript - 通过 Angular 在 json 对象中显示列表的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68440168/