Search code examples
angularangularfire2rxjs6

rxjs6 filter Observable<Array<any>>


I have an angularFirestore observable array inside users.service.ts:

$users: Observable<Array<any>>;
constructor()
{
    this.$users = this.angularFirestore.collection('users').valueChanges();
}

This is the object class:

class User
{
    name: string;
    status: boolean;
    index: number;
}

I need to filter based on multiple fields but somehow using the following code in users.component.ts does not subscribes any results:

users: Users[];
ngOnInit()
{
    this.usersService.$users.pipe
    (filter((user: User) => user.name == 'some value'))
    .subscribe((users: User[]) =>
    {
        this.users = users;
    });
}

My end goal is to be able to filter to include user.name search string and user.status == true and exclude the rest of the invalid results.

I would like to do this without pipes. would appreciate any help on correcting and improving upon the existing code to achieve the above. Thanks in advance!


Solution

  • Not really sure what your issue is with .pipe. But you could also do that once you get your array inside .subscribe

    users: Users[];
    ngOnInit() {
      this.usersService.$users
        .subscribe((users: User[]) => {
          this.users = users.filter(user => user.status && user.name === 'some value')
        });
    }
    

    BTW, it's NOT a bug as mentioned by kunwar97. This is the only way you can apply operators to Observables in Rxjs6.