【问题标题】:Best way to display a list within a json object via Angular通过 Angular 在 json 对象中显示列表的最佳方式
【发布时间】:2021-09-27 02:21:05
【问题描述】:

我试图通过角度在 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&lt;any&gt; 中丢失的错误。

我也尝试了 ngFor 与 KeyValue 管道,但它也没有正常工作。

我将不胜感激。

【问题讨论】:

  • 这是一个承诺,所以要么使用 async/await 要么只做this.pService.getJson().then(data =&gt; this.data = data);

标签: javascript angular typescript frontend


【解决方案1】:

你能试试这段代码被剪掉吗

    ngOnInit(){
    this.pService.getJson().
     then(response => {
       this.json = response;
     })
  }

【讨论】:

    【解决方案2】:

    问题是this.pService.getJson() 返回一个Promise 引用。要了解更多关于Promise的信息,请点击here

    所以这是您需要应用的修复:

    ngOnInit() {
      // you will need to implement the then call of the promise
      this.pService.getJson()
        .then((result) => {
          this.json = result;
          // then call the change detection, I will explain this below
          return this.cd.detectChanges();
        });
    }
    

    此外,这可能会给您带来 changeDetector 问题,因此您可能需要 在组件构造函数中注入ChangeDetectorRef

    constructor(
        private router: Router,
        public app: AppService,
        public pService: Service,
        public cd: ChangeDetectorRef,
    ) {
    }
    

    这应该可以解决您的问题,但我会进一步建议您阅读有关承诺的更多信息 并考虑使用Observable 而不是Promise,请在Observable 上查看link

    【讨论】:

      猜你喜欢
      • 2018-11-02
      • 1970-01-01
      • 2015-10-21
      • 2015-03-15
      • 2012-04-06
      • 1970-01-01
      • 2020-06-04
      • 2016-01-02
      • 2016-05-04
      相关资源
      最近更新 更多