我在Angular 2.3.1上,对于Angular和基于事件的编程我都很新。我有两个订阅,route.params.subscribe
和engineService.getEngines()
。在我的onInit
中,我想在完成this.route.params.subscribe
和this.engineService.getEngines().subscribe
之后致电getEngineName
。如何在两个Angular 2订阅完成后调用一个函数?
之所以这样:getEngineName
功能依赖于engineId
从queryParams和engines
阵列被getEngines()
呼叫完成后填充。
我看过flatMap
和switchMap
但我没有完全理解它们。
这是组件的代码:
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;
})
}
}
您可以使用combineLatest。您的问题与此类似:http://stackoverflow.com/questions/40872357/waiting-for-ngrx-action-before-loading-page-with-url-parameter/40905330#40905330 With combineLatest you do not need嵌套订阅。 – chrigu