简体   繁体   中英

Best way to display a list within a json object via Angular

im trying to display the objects within a list within a json object via angular, but i can't really get it to work.

The json is delivered via a service as a resolved Promise:

getJson(): Promise<any> {
    return Promise.resolve(this.testdata);
}

Thus function returns an [object Promise]

The testdata json string is of structure:

{"errorCode":"ok",
 "objList":[{},{},etc.]
}

What i want is to display a list (for example with ngFor) and have access to the properties of the objects within the objList.

My initial idea was to just iterate over the object list with ngFor, to do this i created the following class

export class ExampleComponent implements OnInit {

json : {"objList": []}

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

ngOnInit(){
    this.json = this.pService.getJson()
  }
}

This does not work however, as im getting the error that property objList is missing in type Promise<any> .

I also tried ngFor with KeyValue pipe, however it also didnt work properly.

I'd appreciate any help.

Can you please try this code snipped

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

the issue is that this.pService.getJson() returns a Promise reference. To learn more about Promise click here

So here is the fix you need to apply:

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();
    });
}

Additionally this may cause changeDetector issues for you so you may want to inject the ChangeDetectorRef in the component constructor

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

This should sort you out, but i'd further advise reading more about promises and considering using Observable instead of Promise , check this link on Observable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM