简体   繁体   English

Angular 5-使数据异步

[英]Angular 5 - Getting data async

I'm using a little bit complicated API, and I could use some of your help. 我正在使用一些复杂的API,并且可以使用一些帮助。

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 每个程序包包含10个程序包,但我需要创建所有程序包的列表

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. 我正在从其中一个获取数据:['1','2','3','4','5','1','2','3','4','5' ],然后得到下一个包:['4','5','1','2','3','1','2','3','4','8']和下一个和下一个直到我的状况恢复正常。

So I do it using a do-while loop. 所以我用do-while循环来做。 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. 经过2个小时的尝试,我不知道该怎么做。

I have to wait until that result comes before I decide to increment I and get another pack of data. 我必须等到结果出现后再决定增加I并获取另一包数据。

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 请注意,我不知道您的变量cool是做什么?

You can use Async/await in order to force javascript execution to wait for the return of the asynchronous API calling, like that: 您可以使用Async / await来强制javascript执行以等待异步API调用的返回,如下所示:

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://labs.encoded.io/2016/12/08/asyncawait-with-angular/

https://javascript.info/async-await https://javascript.info/async-await

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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