Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: RxJs switchMap producing error

Tags:

angular

rxjs

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);
})

}

like image 267
koque Avatar asked Apr 02 '26 09:04

koque


2 Answers

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);
}
like image 94
SEY_91 Avatar answered Apr 04 '26 00:04

SEY_91


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);
  }
);}
like image 34
Jb Randria Avatar answered Apr 03 '26 22:04

Jb Randria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!