2017-02-20 60 views
1

我想在我的組件中填充一個名爲processes的數組,該數組是process的數組。每個process也有一個列表tasksObservable.fork加入for循環

/processes/process/{processId}/tasks

我用/processes讓所有的過程,最初填充processes陣列:

所以目前,我與兩個API調用它們的工作。然後我使用每個process的進程ID調用第二個API來獲取該進程的任務。

目前,我的代碼看起來是這樣的:

this.processes.forEach((process, index) => { 
    myService.getTasks().subscribe((tasks) => { 
     process.tasks = tasks; 
    }) 
}) 

我明白,我可以創造可觀的數組,並使用Observable.forkJoin()等待所有這些異步調用來完成,但我希望能夠到爲每個呼叫定義訂閱回調函數,因爲我需要參考process。關於如何解決這個問題的任何想法?

+0

Observable.forkJoin將返回任務數組相互匹配過程的索引在你的進程數組中 –

回答

4

使用for循環發出多個HTTP請求,然後單獨訂閱它們應該被避免,以避免打開多個Observable連接。

正如@Juan Mendes所述,Observable.forkJoin將返回一個匹配您的進程數組中每個進程索引的任務數組。您也可以將任務分配給每一個過程,他們到達如下:

getTasksForEachProcess(): Observable<any> { 

    let tasksObservables = this.processes.map(process, processIdx) => { 
     return myService.getTasks(process) 
      .map(tasks => { 
       this.processes[processIdx].tasks = tasks; // assign tasks to each process as they arrive 
       return tasks; 
      }) 
      .catch((error: any) => { 
       console.error('Error loading tasks for process: ' + process, 'Error: ', error); 
       return Observable.of(null); // In case error occurs, we need to return Observable, so the stream can continue 
      }); 
    }); 

    return Observable.forkJoin(tasksObservables); 
}; 

this.getTasksForEachProcess().subscribe(
    tasksArray => { 
     console.log(tasksArray); // [[Task], [Task], [Task]]; 
     // In case error occurred e.g. for the process at position 1, 
     // Output will be: [[Task], null, [Task]]; 

     // If you want to assign tasks to each process after all calls are finished: 
     tasksArray.forEach((tasks, i) => this.processes[i].tasks = tasksArray[i]); 
    } 
); 

也請看看這篇文章:Send multiple asynchronous HTTP GET requests