Angular 4 chaining http get request(Promises)

2019-06-14 08:00发布

问题:

I would like to receive some help on the following code:

fillDataAssociationsArray(DataAssociationIDS: string[]) {
const promise = new Promise((resolve, reject) => {
  for (const id of DataAssociationIDS) {
    this.api.getDataAssociationByID(id).toPromise().then(
      data => {
        this.DataAssociations.push(data.body.entities.DATAASSOCIATIONS[0]);
      });
  }
  resolve();
});

return promise;}

In the code above I am trying to convert an array of DataAssociationIDS to DataAssociation objects, and than pushing them to a local array of DataObjects[]. I get each DataObject with an id from the array(parameter) and than performing a get Request to the API which returns the correct DataObject from the Backend.

public getDataAssociationByID(dataAssociationID: string) {
return this.http.get<DataAssociationInterface>(this.apiURL + 'typeOne=DATAASSOCIATIONS&id=' + dataAssociationID,
 { observe: 'response' });}

I want to chain some HTTP get requests from my api, where each request depends on the result of the previous request. So my idea was to make promises of these requests and use the then() method as follows: firstRequest().then( SecondRequest().then(...)) and so to follow.

My try

ngOnInit() {
   this.fillDataAssociationsArray(this.extractDataAssociationIdsFromActivities()).then(
  () => console.log(this.DataAssociations)
  // () => console.log(this.DataAssociations[0].languages.DUT.name)
);}

First result Second line result

This first line in the then()-block prints the correct resulting local array however, when I try the second line(commented) which prints the name of the item I get undefined??? And when I chain the next request it also cant read undefined obviously.

回答1:

I think you have an async issue here.

Its possible that you are resolving your promise before you are getting your result from http get call.

I think the best way to fix this issue would be to add an api call to take an array of ids and return an array of results. However for this use case my approach would be:

fillDataAssociationsArray(DataAssociationIDS: string[]) {
const promise = new Promise((resolve, reject) => {
  for (const id of DataAssociationIDS) {
    this.api.getDataAssociationByID(id).toPromise().then(
      data => {
        this.DataAssociations.push(data.body.entities.DATAASSOCIATIONS[0]);
        if (this.DataAssociations.length === DataAssociationIDS.length) {
          resolve();
        }
      });
  }
});

return promise;}