Angular:RxJs switchMap 产生错误

koq*_*que 2 rxjs angular

我正在完全按照 Angular 文档中所示对我对 switchMap 的使用进行建模:

角度文档实现:

ngOnInit() {
  this.hero$ = this.route.paramMap
    .switchMap((params: ParamMap) =>
      this.service.getHero(params.get('id')));
Run Code Online (Sandbox Code Playgroud)

}

我的实现:

ngOnInit() {
    let product$ = this.route.paramMap
     .switchMap((params: ParamMap) =>
     this.getProduct(params.get('id')));
Run Code Online (Sandbox Code Playgroud)

}

我的 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<{}>'.
Run Code Online (Sandbox Code Playgroud)

这是我的 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);
})
Run Code Online (Sandbox Code Playgroud)

}

SEY*_*_91 7

您的方法类型是无效的,因为您没有返回任何值。那么你必须像这样改变它。

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);
}
Run Code Online (Sandbox Code Playgroud)

如果你像这样重构你的代码,它会更具可读性。

 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);
}
Run Code Online (Sandbox Code Playgroud)