3

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

}

2 Answers 2

8

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.