Search code examples
angularrxjsangular-httpclient

Filtering response from httpClient in Angular


I have a response from mock API, for example this:

{
    "results": [
        {
            "gender": "male",
            "name": {
                "title": "Monsieur",
                "first": "Jérémy",
                "last": "Legrand"
            },
            "dob": {
                "date": "1969-01-31T18:22:15.969Z",
                "age": 53
            },
            "nat": "CH"
        },
        {
            "gender": "female",
            "name": {
                "title": "Mrs",
                "first": "Marèl",
                "last": "Pasterkamp"
            },
            "dob": {
                "date": "1947-04-14T12:01:09.994Z",
                "age": 75
            },
            "nat": "NL"
        }
    ],
    "info": {
        "seed": "5298c9fc807f512f",
        "results": 2,
        "page": 1,
        "version": "1.4"
    }
}

As you see, api returns data and some meta. In my Angular service I want to filter this response and fetch only 'results'. What is the best way to do it in this case? Is it good solution to filter in pipe or it is better to filter result after subscribe() ?

Example place in code:

    this.http.get('url')
      .pipe(
      // filter here
      );

Solution

  • You can use the rxjs operator map:

    @Injectable({...})
    export class MyService {
      constructor(private http: HttpClient) {}
    
      getOnlyResults(): Observable<YourTypeHere> {
        return this.http.get('.....').pipe(
          map((response) => response.results) // get only results
        );
      }
    }
    

    You shouldn't subscribe, for that, you need to pipe it, and let the components subscribe to it using the async pipe if you can