koque
koque

Reputation: 2256

ActivatedRoute.paramMap.switchMap Error

In the ngOnInit method of my component the following line is producing an error.

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

This is the error produced:

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)

This is the component:

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

}

At the moment, BrandService.getProductsForType() method is returning an empty array:

@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([])
  }
}

Upvotes: 0

Views: 620

Answers (1)

Fredrik Lundin Grande
Fredrik Lundin Grande

Reputation: 8186

You need to import the switchMapoperator to use it. Add the following line at the top of your file, where you have your other imports:

import 'rxjs/add/operator/switchMap';

Upvotes: 1

Related Questions