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

激活路线。paramMap。switchMap错误

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

    在我的组件的ngOnInit方法中,下面的行产生了一个错误。

    this.products$ = this.route.paramMap.switchMap((params: ParamMap) =>
      this.getProductsForType(params.get('type'))); 
    

    这是产生的错误:

    BrandComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: this.route.paramMap.switchMap is not a function
    at BrandComponent.ngOnInit (brand.component.ts:22)
    at checkAndUpdateDirectiveInline (core.js:12369)
    at checkAndUpdateNodeInline (core.js:13893)
    at checkAndUpdateNode (core.js:13836)
    at debugCheckAndUpdateNode (core.js:14729)
    at debugCheckDirectivesFn (core.js:14670)
    at Object.eval [as updateDirectives] (BrandComponent_Host.ngfactory.js? [sm]:1)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:14655)
    at checkAndUpdateView (core.js:13802)
    at callViewAction (core.js:14153)
    

    这是组件:

    export class BrandComponent implements OnInit {
      private products:Product[];
      private products$: Observable<Product[]>;
    
      constructor(private route:ActivatedRoute,
        private brandService: BrandService) { }
    
      ngOnInit() {    
        this.products$ = this.route.paramMap.switchMap((params: ParamMap) =>
          this.getProductsForType(params.get('type'))); 
      }
    
      private getProductsForType(type) {
        console.log('BrandComponent.getProductsForType() called')
        return this.brandService.getProductsForType(type);
      }
    
    }
    

    目前,BrandService。getProductsForType()方法返回空数组:

    @Injectable()
    export class BrandService {
      private productsUrl:string = '/api/products/all';
      private products:Product[];
    
      constructor(private http:HttpClient,
        private dataService:DataService) { }
    
      public getProductsForType(type:string)  : Observable<Product[]> {
        console.log('BrandService.getProductsForType() called')
        // return this.dataService.getProductsForType(type);
        return of([])
      }
    }
    
    1 回复  |  直到 8 年前
        1
  •  1
  •   Fredrik Lundin Grande    8 年前

    您需要导入 switchMap 操作员使用它。在文件顶部添加以下行,其中包含其他导入:

    import 'rxjs/add/operator/switchMap';
    
    推荐文章