1

I have a problem very similar to : Why is Angular not choosing correct overload for HttpClient.get(...)?

and this:

Angular HttpClient return expecting observable<HttpEvent<any> rather than observable<any>

but neither of those solutions are working.

My code looks like this:

 getTopology(): Observable<Topology> {
    var me = this;
    let headers = new HttpHeaders({
        'Content-Type': 'application/json'
    });
    let params = new HttpParams();
    let options = {headers: headers, params: params};
    let url = this.url;
    return this.http.getTyped<Topology>(url, options);
}


 getTyped<T>(
     url: string,
     options: {
         headers: HttpHeaders;
         observe?: 'body';
         params?: HttpParams;
         reportProgress?: boolean;
         responseType?: 'json';
         withCredentials?: boolean;
     },
     signRequest = true
 ): Observable<T> {
     options.headers = options.headers.append(
         'Authorization',
         `Bearer ${localStorage.getItem('token')}`
     );
     return this.http.get<T>(url, options);
 }

It is pointing to this get:

 get(url: string, options?: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<Object>;

Instead of this get:

get<T>(url: string, options?: {
    headers?: HttpHeaders | {
        [header: string]: string | string[];
    };
    observe?: 'body';
    params?: HttpParams | {
        [param: string]: string | string[];
    };
    reportProgress?: boolean;
    responseType?: 'json';
    withCredentials?: boolean;
}): Observable<T>;

Any suggestions? Also I am using Angular 6.0.6

iamcootis
  • 2,203
  • 3
  • 18
  • 22

1 Answers1

3

It happens when you want to wrap HttpClient methods, because you pass options dynamically it can't detect type of options. If you change the line

return this.http.get<T>(url, options);

to this

return this.http.get<T>(url, {
     headers: yourHeaders;
     params: params;
 });

it will work. I had the same problem when intended to wrap HttpClient methods but then gave up because of this.

Hikmat G.
  • 2,591
  • 1
  • 20
  • 40
  • Waste few hours to find your solution works, but do you possibly why this happens? And what if I need to dynamically assign value to 'options'? – Junlong Wang Apr 17 '20 at 10:14
  • To be honest I can't simulate the problem now ). Copy pasted `getTyped` method to my project and it points to correct overload. In fact my answer doesn't make sense, because options has correct type defined as parent function's argument. – Hikmat G. Apr 18 '20 at 09:26