我正在模拟我对switchMap的使用,正如Angular文档中所示:
Angular doc实现:
ngOnInit() {
this.hero$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')));
}
我的实施:
ngOnInit() {
let product$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.getProduct(params.get('id')));
}
我的switchmap实现在编辑器中产生以下错误:(不是运行时错误)
[ts]
Argument of type '(params: ParamMap) => void' is not assignable to parameter
of type '(value: ParamMap, index: number) => ObservableInput<{}>'.
Type 'void' is not assignable to type 'ObservableInput<{}>'.
这是我的getProduct()方法:
private getProduct(id:string) {
this.dataService.getProduct(id).subscribe(product => {
this.product = product;
this.currentImage = product.image[0];
console.log('product = ', this.product)
return of(product);
})
}
答案 0 :(得分:2)
您的方法类型无效,因为您没有返回任何值。 然后你必须像这样改变它。
private getProduct(id:string) {
this.dataService.getProduct(id).subscribe(product => {
this.product = product;
this.currentImage = product.image[0];
console.log('product = ', this.product);
});
return of(this.product);
}
如果您像这样重构代码,它会更具可读性。
product$: Observable<any>;
ngOnInit() {
this.product$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.getProduct(params.get('id')));
this.product$.subscribe(product => {
this.currentImage = product.image[0];
});
}
private getProduct(id:string) {
return this.dataService.getProduct(id);
}
答案 1 :(得分:0)
ngOnInit() {
this.route.paramMap.pipe(
switchMap((params: ParamMap) => {
return this.palmaresService.getPalmaresForAnUser(params.get('id'));
})
).subscribe(
result => {
this.userDetails = result as any;
},
error => {
console.log('Error on fetching data: ', error);
}
);}