代码之家  ›  专栏  ›  技术社区  ›  Stéphane GRILLON

forkjoin subscribe(rxjs 6)的角度6返回结果

  •  1
  • Stéphane GRILLON  · 技术社区  · 6 年前

    简单案例和确定:

    const observables = [];
    for (let i = 0; i < this.originalData.length; i++) {
          observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
           };
    
    forkJoin(...observables).subscribe(dataGroup => {
        console.log(dataGroup.id);
    });
    

    控制台是 1 2 3 4 5

    我和Ko的更复杂案例:

    private todo(foot) {
        const observables = [];
        for (let i = 0; i < this.originalData.length; i++) {
          observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
        };
    
        forkJoin(...observables).subscribe(dataGroup => {
          console.log(dataGroup);
          // How to put all dataGroup id in foot.param ?
        });
    
        return this.dashboardService.getFoo(foot);
    }
    

    代码执行此操作:

    return this.dashboardService.getFoo(foot);
    

    在此之前:

    console.log(dataGroup);
    

    如何等待订阅结束,并在重新运行之前(在末尾)在foot.param中添加/mofify所有数据组ID?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Nima Hakimi    6 年前

    这个 todo 函数本身应该是异步的,因此它应该返回 Observable :

    private todo(foo): Observable<any> {
        const observables = [];
        for (let i = 0; i < this.originalData.length; i++) {
          observables.push( this.dashboardService.getDetails(this.id1[i], this.id2[i])
        };
    
        // notice that dataGroup is an array of latest value of all observables
       return forkJoin(observables).map((dataGroup: any[]) => {
          // do whatever you want to foo before calling the function
          // remember you need to also merge if getFoo returns an observable as well
          // but I assume it doesn't
          return this.dashboardService.getFoo(foo);
        });
    }