Angular:RXJS SwitchMap产生误差



我正在建模我对switchmap的使用,如"角文档"中所示:

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

}

您的方法类型是无效的,因为您没有返回任何值。然后,您必须这样更改。

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

最新更新