筛选BehaviourSubject.asObservable()问题

时间:2018-10-17 13:57:05

标签: angular rxjs behaviorsubject

我正在通过HttpClient加载数据,并将其发布为BehaviourSubject:

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

在使用中,我正在通过API端点加载数据:

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

如您所见,我想获得所有状态等于1的汽车。 当我从组件中调用此函数时,我什么也没得到:

Component

cars: Observable<Car[]>;

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

如果我返回未过滤的BehaviourSubject,我会毫无问题地获取未过滤的数据

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

我在做什么错?

1 个答案:

答案 0 :(得分:1)

我怀疑您需要订阅从getFilteredCars()方法返回的可观察对象。

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