javascript - 通过 Angular 在 json 对象中显示列表的最佳方法

标签 javascript angular typescript frontend

我试图通过 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/

相关文章:

javascript - Yeoman 生成器在全局安装时找不到 .yo-rc.json 文件

angular - 如何在 Angular 中使用 mat-text-column

javascript - 我应该取消订阅 Angular 表单更改吗?

Angular - 由于运行时错误,无法使 sortablejs 工作

angular - 如何更改 Cloud Firestore 中数组内的对象?

javascript - 如何在 VSCode 的同一个项目中对 .ts 文件和 .js 文件运行 typescript-eslint

javascript - 如何基于这个简单对象构建这个复杂的数组

javascript - 在 Javascript 中禁用文本字段自动对焦

typescript - Visual Studio TypeScript 在保存时编译失败, "Project contained errors"但未显示任何错误?

javascript - 使用本地存储进行应用内购买和应用更新