我正在为我的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);
}
但是,我在控制台中收到错误。关于不能读取未定义的属性'name‘。我不认为我正在从resolve函数的第二个版本中恢复一个已完成的可观察对象。
发布于 2018-08-16 05:35:04
代码应该是
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;
})
)
)
);
否则,路由器在第一个可观测对象发出后立即将结果提供给组件,而不等待第二个可观测对象。
https://stackoverflow.com/questions/51866357
复制相似问题