Romain Ensminger
Romain Ensminger

Reputation: 93

Angular 4-5 HttpClient strong typing of http get

I use a helper service that simplifies httpClient calls. I would like to strongly type the Observable that is returned.

my service where I use the api Service and try to get a strongly typed observable that emits >.

export class ApiUser(){
  constructor(private api: Api){}

  getUsers(url? : string): Observable<Array<User>>{
    return this.api.get<Array<User>>('users'); //here I get errors on types.
  }
}

my api helper service, where the type should be passed :

    import { HttpClient, HttpParams } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    import {Observable} from "rxjs/Observable";
    import {User} from "../../interfaces/interfaces";

    /**
     * Api is a generic REST Api handler.
     */
    @Injectable()
    export class ApiService {
      constructor(public http: HttpClient) {}

      get(endpoint: string, params?: any, reqOpts?: any){
       
        return this.http.get('https://sub.domain.com/api/v1/' + 
     endpoint,reqOpts);
      }
    }

So the issue is that this is likely not the right way to strongly type, it works if I type on this.http.get inside the api helper service, but that defeats the purpose of having a helper service.

Upvotes: 2

Views: 2891

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93043

You need to provide a type variable to your ApiService.get function, because HttpClient.get assumes a standard Object when a type is not provided. In order to do that, you can update ApiService.get to use such a type variable (e.g. T), like so:

get<T>(endpoint: string, params?: any, reqOpts?: any) {
    return this.http.get<T>('https://sub.domain.com/api/v1/' + 
         endpoint,reqOpts);
}

Note you specify <T> both as part of the function declaration (get<T>) and as the parameter being passed into HttpClient.get.

Upvotes: 5

Related Questions