Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading