0

I have a service carriersService with method getAll(), which returns an Observable<Carrier[]>. In my component, I'm trying to read route parameter carrierId, find the carrier with such carrierId and assign it to a local variable

let carrier = null;

this.route.paramMap.pipe(
      switchMap(
        (params: ParamMap) => this.carriersService.getAll()));

I need to find a single Carrier from an Observable of Carrier[] using params.get('carrierId') and assign it to local carrier variable.

1 Answers1

0

combineLatest will emit once both observables have emitted, this allows you to use the route param to find the carrier in the array.

combineLatest(
  this.route.paramMap.pipe(map(p => p.get('carrierId'))),
  this.carriersService.getAll()
).pipe(
  map(([carrierId, carriers]) => carriers.find(carrier => carrier.id === carrierId))
).subscribe(carrier => {
  this.carrier = carrier;
});
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
  • Thank you. What I found is combineLatest in this form is deprecated. New version takes an array of observables as an argument. Like this: ```combineLatest([this.route.paramMap.pipe(map(p => p.get('carrierId'))), this.carriersService.getAll()]).pipe( map(([carrierId, carriers]) => carriers.find(carrier => carrier.id === carrierId)) ).subscribe(carrier => { this.carrier = carrier; });``` – Alex Dantsev Jul 09 '20 at 17:16