I am modeling my use of switchMap exactly as shown in the Angular documentation:
Angular doc implementation:
ngOnInit() {
this.hero$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.service.getHero(params.get('id')));
}
My implementation:
ngOnInit() {
let product$ = this.route.paramMap
.switchMap((params: ParamMap) =>
this.getProduct(params.get('id')));
}
My switchmap implementation produces the following error in the editor: (not a runtime error)
[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<{}>'.
This is my getProduct() method:
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);
})
}
Your method type is void because you are not returning any value. Then you have to change it like this.
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);
}
It would be more readable if you refactor your code like this.
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);
}
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);
}
);}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With