javascript - ActivatedRoute.paramMap.switchMap 错误

标签 javascript angular typescript rxjs

在我的组件的 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([])
  }
}

最佳答案

您需要导入switchMap运算符才能使用它。在文件顶部添加以下行,其中包含其他导入:

import 'rxjs/add/operator/switchMap';

关于javascript - ActivatedRoute.paramMap.switchMap 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49946808/

相关文章:

javascript - HTML:将 <div> 放在 <col> 中

javascript - Puppeteer 不等到页面加载完成

angular - 如何从 visual studio 2015 update 3 的构建中排除 node_module 文件夹

angular - 使用此 splice() 导致页面刷新的原因是什么?

typescript - 如何使用 Angular 2 管道对对象列表进行排序

angular - 更改检测似乎在动态实例化的组件中不起作用

javascript ken ken 拼图生成器

Angular 2 UI-路由器身份验证

reactjs - Next.js api 路由器抛出 404

javascript - 禁用 turobolinks 来服务页面特定的 javascript