【问题标题】:Angular 5 - Getting data asyncAngular 5 - 获取数据异步
【发布时间】:2018-07-10 09:55:59
【问题描述】:

我正在使用有点复杂的 API,我可以使用你的一些帮助。

就是这样。我在包中获取重要数据。每个包包含 10 个,但我需要创建一个列表

例如。

我从其中一个获取数据:['1', '2', '3', '4', '5','1', '2', '3', '4', '5'] 然后我得到下一个包: ['4', '5','1', '2', '3', '1', '2', '3', '4', '8 '] 下一个和下一个,直到我的条件成立。

所以我使用 do-while 循环来完成。看起来是这样的:

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

问题是我不知道这个循环会做多少次,所以我需要一个一个地完成动作。经过将近 2 小时的尝试,我不知道如何做好。

我必须等到结果出来后才决定增加 I 并获取另一包数据。

【问题讨论】:

    标签: angular asynchronous async-await


    【解决方案1】:

    do/while 将是错误的构造。请改用递归。

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

    请注意,我不知道您的变量 cool 是什么或做什么

    【讨论】:

    • 太棒了。工作完美。从来没有想过以这种方式进行这样的操作。谢谢。
    【解决方案2】:

    您可以使用 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);
    }
    

    更多信息请查看以下链接:

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

    https://javascript.info/async-await

    【讨论】:

      猜你喜欢
      • 2020-08-10
      • 1970-01-01
      • 2013-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 2017-12-23
      相关资源
      最近更新 更多