代码之家  ›  专栏  ›  技术社区  ›  koque

角度:RxJs switchMap生成错误

  •  3
  • koque  · 技术社区  · 8 年前

    我正在为我对switchMap的使用建模,正如Angular文档中所示:

    角度文档实现:

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

    }

    2 回复  |  直到 8 年前
        1
  •  8
  •   SEY_91    8 年前

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

    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);
    }
    
        2
  •  2
  •   Jb Randria    7 年前
    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);
      }
    );}