私はAngular 2.3.1を使用しており、AngularとEventの両方のプログラミングにはかなり新しいです。私は2つのサブスクリプション、route.params.subscribe
とengineService.getEngines()
を持っています。私のonInit
ではthis.route.params.subscribe
とthis.engineService.getEngines().subscribe
の後にgetEngineName
に電話したいと思っています。このため2つのAngular 2サブスクリプションの完了後に関数を呼び出す方法は?
理由:getEngineName
機能getEngines()
コールの完了後に取り込まれqueryParamsとengines
アレイからengineId
に依存します。
私はflatMap
とswitchMap
を見ましたが、私は完全に理解していませんでした。あなただけroute.params
コールバック内部のロジックを移動しないのはなぜ
export class ItemListComponent implements OnInit {
items: Item[];
engines: Engine[];
private engineId: number;
constructor(
private router: Router,
private route: ActivatedRoute,
private itemService: ItemService,
private engineService: EngineService
) {}
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.engineId = +params['engineId'];
// itemService is irrelevant to this question
this.itemService.getItems({engineId: this.engineId})
.subscribe((items: Item[]) => {
this.items = items;
});
});
this.engineService.getEngines()
.subscribe(engines => this.engines = engines);
// This should only run after engineId and engines array have been populated.
this.getEngineName(this.engineId);
}
getEngineName(engineId: number) {
this.engines.find((engine) => {
return engine.id === engineId;
})
}
}
など
this.engineId
のような任意の状態を維持避けてきました。あなたの問題はこれに似ています:http://stackoverflow.com/questions/40872357/waiting-for-ngrx-action-before-loading-page-with-url-parameter/40905330#40905330 combineLatestでは、あなたは必要ありませんサブスクリプションをネストする – chrigu