输入'Observable<HttpEvent<T>>'不可分配到类型 'Observable<T>' [英] Type 'Observable<HttpEvent<T>>' is not assignable to type 'Observable<T>'
本文介绍了输入'Observable<HttpEvent<T>>'不可分配到类型 'Observable<T>'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题出在第 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)
如果我删除第二个参数 this.getHttpParams(obj)
,那么它运行良好.
If I remove the second parameter, this.getHttpParams(obj)
, then it works well.
但是我需要传递参数.
如何解决这个问题?
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;
}
}
推荐答案
get
有很多重载,一些返回Observable
,而另一些返回Observable
.如果 getHttpParams
的返回值是 any
,它认为你会得到后者.
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} { ... }
这篇关于输入'Observable<HttpEvent<T>>'不可分配到类型 'Observable<T>'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文