JSONデータを外部ソースから一連の「カテゴリデータ」として取り出し、ユーザーに基づいてそのデータをフィルタリングするforループのサブスクリプションがあります現在位置。私が必要とするのは、すべてのサブスクリプションが完了するのを待ってから、それから私のアプリが進むことができるようにすることです。今は、すべてのサブスクリプションが完了するまで待つのではなく、いくつかの処理を完了してから、別のサブスクリプションがバックグラウンドで続行されます。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;
});
}
、私が決定する方法のように、本当にいただきたいですすべてのサブスクリプションが完了したとき。どんな助けもありがとう!
グレートと簡単なソリューションを!魅力的に働いた。ありがとうございました! – AlexT