Rishav Tandon
Rishav Tandon

Reputation: 1261

filter result of observable

I have a service which returns an observable of organization object, and I want to filter the result based on organizationID I pass.

Currently I am doing something like this, but it returns me all the values instead of filtered one.

filteredOrganization(organizationId: number) {
  return this.http.get < Organization[] > (this.baseUrl + '/list').pipe(
    map(organizations => {
      return organizations.filter(organization => {
        organization.id === organizationId;
        return {
          id: organization.id,
          name: organization.name,
        };
      });
    }),
  );
}

For Eg. service returns [{1: abc, 2: def, 3: pqr}]

What I want I pass 1 as organization Id and want result [{1: abc}]

What I am getting [{1: abc, 2: def, 3: pqr}]

Upvotes: 2

Views: 648

Answers (3)

Jose Marin
Jose Marin

Reputation: 964

The example you are showing you don't need to do map, as the output format is the same as the input. You just need to do filter.

filteredOrganization(organizationId: number) {
    return this.http.get<Organization[]>(this.baseUrl + '/list').pipe(
        filter(organization => organization.id === organizationId))
});

Upvotes: 3

farhodius
farhodius

Reputation: 530

Your map function within the pipe operator should filter the results by org ID first then map the filtered results to the desired form and then return to the subscriber of a stream:

filteredOrganization(organizationId: number) {
  return this.http.get < Organization[] > (this.baseUrl + '/list').pipe(
    map(organizations => {
      return organizations.filter((org) => org.id === organizationId).map((org) => {
        return { id: organization.id, name: organization.name};
      });
    }),
  );
}

Upvotes: 0

Nilo Alan
Nilo Alan

Reputation: 990

Take a look at this:

https://stackblitz.com/edit/angular-ivy-euxd7m?file=src/app/app.component.ts

filter (rxjs) expects a boolean to be returned and, in this case, need not specify the return as an object.

You're already making a map, and just filtering...

this.appService.get()
     .pipe(
        map(organizations => {
          return organizations.filter(x => x.id === organizationId);
        })
      )
      .subscribe(val => console.log(val));

Upvotes: 5

Related Questions