简体   繁体   中英

Angular 5 - Getting data async

I'm using a little bit complicated API, and I could use some of your help.

There it is. I'm getting important data in packages. Each package contains 10 of them, but I need to create a list of all

eg.

I'm getting data from one of them : ['1', '2', '3', '4', '5','1', '2', '3', '4', '5'] and then I get next package : ['4', '5','1', '2', '3', '1', '2', '3', '4', '8'] and next one and next one till my condition stands.

So I do it using a do-while loop. It looks like that :

do {
  this.getMyDataPart(i).then( result => {
     list = list.concat(result);
     i++;
  });
} while(cool);

getMyData(idofPackege: number): Observable<DataObject> {
  return this.http.get<DataObject>(this.apiURL + idofPackege);
}

The problem is that I don't know how many times this loop will be made, so I need the actions to be done one by one. And after almost after 2 hours of trying I don't know how to do it well.

I have to wait until that result comes before I decide to increment I and get another pack of data.

A do/while would be the wrong construct to use. Use recursion instead.

list: any[];

ngOnInit() {
  this.list = [];
  myRecursiveFunction(0);
}

myRecursiveFunction(i: number) {
    this.getMyData(i).subscribe(result => {
        this.list = this.list.concat(result);
        if(this.cool) { 
          i++;
          this.myRecursiveFunction(i);
        }
    });
}

getMyData(idofPackege: number): Observable<any[]> {
  return this.http.get<DataObject>(this.apiURL + idofPackege);
}

note that I have no idea what your variable cool is or does

You can use Async/await in order to force javascript execution to wait for the return of the asynchronous API calling, like that:

async myAsyncFunction() {
    do {
      const parcialList = await this.getMyDataPart(i);
      list = list.concat(parcialList);
      i++;             
   } while(cool);
}   

getMyData(idofPackege: number): Observable<DataObject> {
   return this.http.get<DataObject>(this.apiURL + idofPackege);
}

See the following links for futher informations:

https://labs.encoded.io/2016/12/08/asyncawait-with-angular/

https://javascript.info/async-await

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