Search code examples
angularrxjsbehaviorsubject

Filtering BehaviourSubject.asObservable() problem


I am loading data through HttpClient and publish them as BehaviourSubject:

    export interface Car {
      id:number;
      make: string;
      status: number;
    }

In service I am loading data through API endpoint:

private cars = new BehaviorSubject<Car[]>([]);

constructor( private http: HttpClient) { 
    this.loadCars();
  }

loadCars() {
    this.http.get<Car[]>('/api/cars')
    .subscribe((cars) => this.cars.next(cars));
  }

getFilteredCars() {
   return this.cars.asObservable()
    .pipe(
      map( (cars) => cars.filter( car => car.status === 1)
      )
      );
}

As you can see I want to get all cars that has status equal to 1. When I call this from my component I don't get anything:

Component

cars: Observable<Car[]>;

  constructor(private carService: CarService) { 
    this.cars = carService.getFilteredCars();
  }

I am getting unfiltered data without any problem If I am returning unfiltered BehaviourSubject:

getFilteredCars() {
       return this.cars.asObservable();
    }

What am I doing wrong?


Solution

  • I suspect you need to subscribe to the observable being returned from your getFilteredCars() method.

    carService.getFilteredCars().subscribe(data=>this.cars = data);