0

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
      );
2
  • Up to you, try one and see how it feels. Filtering in the service means not exposing transport details to the rest of the app, so I'd start there. Either way you should type the response so the compiler can actually help you with the filtering. Commented Aug 17, 2022 at 13:33
  • It's better to do it after subscribe() and also better to add error() as well. Commented Aug 17, 2022 at 13:33

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.