2017-06-26 108 views
2

我在for循環中訂閱了一個for循環,它將JSON數據從外部源獲取爲一系列「類別數據」,然後根據用戶篩選該數據當前位置。我需要的是等待所有訂閱完成,然後才能繼續執行我的應用。現在,它不會等待所有訂閱完成,它只完成一些訂閱,然後繼續,而其他訂閱在後臺繼續。如何在繼續執行之前等待for循環中的訂閱

我試過下面的「蠻力」方法,我知道一定數量的類別將被添加到過濾的數組中,並且它可以工作,但我不知道如何使它適用於任何情況。

這裏是我的代碼:

getMultipleCategoryData(categoryIds: string[]) { 
for (let i = 0; i < this.waypointIds.length; i++) { 
//after user selects their categories, its added to waypointNames, and occurences() gets the # of occurences of each waypoint name 
    let occurences = this.occurences(this.waypointNames[i], this.waypointNames); 
    this.categoryApi.getCategoryData(this.waypointIds[i]).toPromise().then(data => { 

    let filteredLocs = data.locations.filter(loc => this.distanceTo(loc, this.hbLoc) < MAX_RADIUS); 
    let foundLocs = []; 
    //fill filteredLocs with first n, n = occurences, entries of data 
    for (let n = 0; n < occurences; n++) { 
     if (filteredLocs[n] != undefined) { 
     foundLocs[n] = filteredLocs[n]; 
     } 
    } 
    //find locations closest to hbLoc (users current location), and add them to waypoints array 
    for (let j = 0; j < foundLocs.length; j++) { 
     for (let k = 0; k < filteredLocs.length; k++) { 
     if (this.distanceTo(this.hbLoc, filteredLocs[k]) < this.distanceTo(this.hbLoc, foundLocs[j]) && foundLocs.indexOf(filteredLocs[k]) < 0) { 
      foundLocs[j] = filteredLocs[k]; 
     } 
     } 
    } 
    if (foundLocs.length > 0 && foundLocs.indexOf(undefined) < 0) { 
     for (let m = 0; m < foundLocs.length; m++) { 
     this.waypointLocs.push(foundLocs[m]); 
     } 
    } 
    }).then(() => { 
    //this hardcoded, brute force method works, but i'd need it to be more elegant and dynamic 
    if (this.waypointLocs.length >= 5) { 
     let params = { waypointLocs: this.waypointLocs, hbLoc: this.hbLoc }; 
     this.navCtrl.push(MapPage, params); 
    } 
    }); 
} 
} 

而且categoryApi.getCategoryData方法:

getCategoryData(categoryId): Observable<any> { 
    // don't have data yet 
    return this.http.get(`${this.baseUrl}/category-data/${categoryId}.json`) 
     .map(response => { 
      this.categoryData[categoryId] = response.json(); 
      this.currentCategory = this.categoryData[categoryId]; 
      return this.currentCategory; 
     }); 
} 

一切工作正常,除了等待訂閱完成,我真的很喜歡的方式來確定當所有訂閱都完成時。任何幫助表示讚賞!

回答

2

您可以收集所有可觀測的數組並用forkJoin等待它們全部完成:

let observables: Observable[] = []; 
for (let i = 0; i < this.waypointIds.length; i++) { 
    observables.push(this.categoryApi.getCategoryData(this.waypointIds[i])) 
} 
Observable.forkJoin(observables) 
    .subscribe(dataArray => { 
     // All observables in `observables` array have resolved and `dataArray` is an array of result of each observable 
    }); 
+0

大和簡單的解決方案!像魅力一樣工作。謝謝! – AlexT

相關問題