[英]Resolver Angular 6
我正在為Angular 6應用程序的路由創建解析器。
當前,我調用一個API並將數據返回給組件,以便它可以在組件的模板中呈現數據。
foo.resolver.ts
@Injectable()
export class FooResolver implements Resolve<any> {
constructor(private fooService: FooService) {}
resolve(route: ActivatedRouteSnapshot) {
return this.fooService.getById(route.paramMap.get('id'));
}
}
foo.component.ts
export class FooComponent implements OnInit {
fooObj: any = {};
constructor(private route: ActivatedRoute) { }
ngOnInit() {
this.fooObj = this.route.snapshot.data.fooObject;
}
}
但是,一旦getById完成並將自定義對象返回給我的foo.component.ts類,就需要更改當前的實現以對另一個API進行子調用。 我試圖編輯resolve函數以反映此要求。
resolve(route: ActivatedRouteSnapshot) {
return this.FooService.getById(route.paramMap.get('id')).pipe(map(result => {
this.fooService.getType().subscribe(results => {
result.type = this.getObject(results, result.typeId);
});
return result;
}));
private getObject(collection: any, id: number): any {
return collection.find(e => e.id == id);
}
但是,控制台出現錯誤。 關於無法讀取未定義的屬性“名稱”。 我不認為我會從第二版的resolve函數中重提一個完整的Observable。
該代碼應為
return this.FooService.getById(route.paramMap.get('id')).pipe(
switchMap(result =>
this.fooService.getType().pipe(
map(results => {
result.type = this.getObject(results, result.typeId);
return result;
})
)
)
);
否則,路由器在第一個可觀察到的對象發出后立即將結果提供給組件,而無需等待第二個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.