Reputation: 2186
The problem is at Line 14
Type 'Observable<HttpEvent<T>>' is not assignable to type 'Observable<T>'.
Type 'HttpEvent<T>' is not assignable to type 'T'.
'HttpEvent<T>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
Type 'HttpSentEvent' is not assignable to type 'T'.
'HttpSentEvent' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.ts(2322)
If I remove the second parameter, this.getHttpParams(obj)
, then it works well.
But I need to pass the parameters.
How to solve this?
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
protected url: string;
constructor(private http: HttpClient) {}
get<T>(endpoint: string, obj: object = null): Observable<T> {
return this.http.get<T>(this.url + endpoint, this.getHttpParams(obj)); // Problem is here.
// If I remove the second parameter: , this.getHttpParams(obj) - then it works good.
// But I need to pass the parameters. How to solve this?
}
protected getHttpParams(obj: object) {
const requestOptions: any = {};
requestOptions.headers = new HttpHeaders({
Accept: 'application/json',
'Content-Type': 'application/json'
});
if (obj !== null) {
requestOptions.params = this.objectToHttpParams(obj);
}
return requestOptions;
}
protected objectToHttpParams(obj: object): HttpParams {
let params = new HttpParams();
for (const key of Object.keys(obj)) {
params = params.set(key, (obj[key] as unknown) as string);
}
return params;
}
}
Upvotes: 0
Views: 3313
Reputation: 122026
get
has a lot of overloads, some that return Observable<T>
and others that return Observable<HttpEvent<T>>
. If the return value from getHttpParams
is any
, it thinks you'll get the latter.
The minimal fix is therefore to be more specific about what that method could return, for example:
protected getHttpParams(obj: object): {headers: HttpHeaders, params?: HttpParams} { ... }
Upvotes: 2