我有一个Angular解析器来为组件提供数据。 我正在使用ngrx。我想检查商店中是否有2条数据(汽车及其制造商),如果没有,请调度一个操作以从2个单独的API中获取数据。我首先根据url参数获取汽车,一旦有了汽车,我就需要让制造商将汽车ID发送给API。 完成这两个请求并且我同时拥有汽车及其制造商后,我想合并数据(将制造商添加为汽车的属性)并在解析器中返回汽车对象。
export class CardResolverService implements Resolve <Observable<any>> {
private cardId: string;
private cardLoaded$ = new Subject();
private makerLoaded$ = new Subject();
private car: Car;
constructor(private store: Store<any>) {
}
// Check if car is in store, otherwise dispatch action to call API
// Once the car is loaded, get its maker based on one of its properties
private initCar(): void {
this.store.select(CarSelectors.getCardById(this.cardId)).pipe(
takeUntil(this.cardLoaded$)
).subscribe((car) => {
if (!car) {
this.store.dispatch(new CarSelectors.LoadCarByIdAction(this.cardId));
} else {
this.cardLoaded$.next(true);
this.car = car;
this.getCarMaker(car.makerId);
}
});
}
private getCarMaker(makerId: string) {
this.store.select(MakerSelectors.getMakerById(makerId)).pipe(
takeUntil(this.makerLoaded$)
).subscribe((maker) => {
if (!maker) {
this.store.dispatch(new MakerActions.LoadMakerByIdAction(makerId));
} else {
this.car.maker = maker;
this.makerLoaded$.next(true);
}
});
}
// I need to wait until both car and maker are loaded to return the car object
private waitForData(): Observable<TeamMemberView> {
return this.carLoaded$.pipe(
withLatestFrom(this.makerLoaded$),
map(() => this.car)
);
}
resolve(route: ActivatedRouteSnapshot): Observable<any> {
// Get car ID from url
this.carId = route.params['carId'];
this.initCar();
return this.waitForData(); // Here is where I need help
}
}
在waitForData方法中,我试图检查获取汽车的观察者和制造者是否都通过主题返回了一个值,如果有,则返回了汽车对象。但是waitForData方法没有返回任何内容。