typescriptrxjsbehaviorsubjectrxjs-filter

how to use Rxjs filter in angular along with BehaviorSubject


I have an array that looks as follows.

data = [
    {
      id: 1,
      name: 'a',
      status: true,
    },
    {
      id: 1,
      name: 'b',
      status: true,
    },
    {
      id: 1,
      name: 'c',
      status: false,
    },
  ];

I have created BehaviorSubject by setting the initial value as the above array.

I want to get the array of data, which status should be true by using rxjs pipe operator. So, the filter process should happen before subscribing to the observable.

I have tried ith the following

 subject: BehaviorSubject<any> = new BehaviorSubject<any>(this.data);
  constructor() {
    this.getSubject()
      .pipe(filter((x) => x.status))
      .subscribe((res) => {
        console.log(res);
      });
  }

  getSubject() {
    return this.subject.asObservable();
  }

Expected output

   [
    {
      id: 1,
      name: 'a',
      status: true,
    },
    {
      id: 1,
      name: 'b',
      status: true,
    }]

Solution

  • Your behaviour subject is returning an Array and rxjs filter is applied on observable not array. You need to apply filter after getting array from observable

    this.getSubject()
      .pipe(map((arr) => arr.filter(x => x.status)))
      .subscribe((res) => {
        console.log(res);
      });