【问题标题】:Angular Asynchronous issue when calling service inside for loop在for循环中调用服务时出现角度异步问题
【发布时间】:2020-06-10 05:32:58
【问题描述】:

如何解决for循环内调用服务的异步问题

  let historyMo =[];
    for (let i = 0; i < history.length; i++) {
             return  this.userService.getNodes(history[i]).subscribe((result: any) => {

                  historyMo.push(result);
              });

           }  

执行 console.log(historyMo) 时有时会返回空数组值

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    避免在一个循环中订阅多个可观察对象。这将导致多个同时订阅和潜在的内存泄漏。

    尝试改用 RxJS forkJoin 或 combineLatest 函数。

    let historyMo =[];
    let requests = [];
    for (let i = 0; i < history.length; i++) {
      requests.push(this.userService.getNodes(history[i]);
    }
    
    forkJoin(requests).subscribe(
      response => {
        this.historyMo = response;
        console.log(this.historyMo);
      }
    );
    

    forkJoin() 仅在所有可观察对象完成时发出 - 使其成为 HTTP 可观察对象的理想选择。

    combineLatest() 用于订阅作为持久数据流的可观察对象。

    此外,任何直接依赖于historyMo 变量的语句都应该在订阅中。它是一个异步变量,不能同步访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-06
      • 2014-05-04
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2011-12-03
      • 1970-01-01
      相关资源
      最近更新 更多