shrewdbeans
shrewdbeans

Reputation: 12549

Angular HTTP Service returns results buried in an object, how to add the type?

I have an Angular service called FilmService, that uses the HttpClient module to fetch data from an API. When a component uses this service, it gets an array of films of type Film. However, the API buries these film objects in a results object (e.g. {results: []}). I've used the map operator to process the Observable and return the results object. However my IDE is complaining about the type of results in my map function:

Property 'results' does not exist on type 'Object'.

How do I correctly type the service method?

Please see my code below.

Interface: Film.ts:

export interface Film {
  id: number;
  title: string;
}

FilmService method:

getMostPopular(): Observable<Film[]> {
  return this.http.get(this.apiUrl, {
    params: {
      api_key: this.apiKey,
      sort_by: 'popularity.desc'
    }
  }).pipe(
    map((films) => films.results) // Property 'results' does not exist on type 'Object'.
  );
}

Upvotes: 2

Views: 633

Answers (1)

Silvermind
Silvermind

Reputation: 5944

If your api buries all responses in the same kind of wrapper object, you can define a generic response type. The HttpClient has a generic type parameter (for most operations), that represents the return type.

Something like this:

export interface ApiResponse<T> {
    results: T;
    errors: string[];
}

then use it in the following manner:

return this.http.get<ApiResponse<Film[]>>(...).pipe(map(response => response.results));

Upvotes: 4

Related Questions