gpt4 book ai didi

javascript - 类型 'Observable>' 不可分配给类型 'Observable'

转载 作者:行者123 更新时间:2023-12-02 21:15:58 25 4
gpt4 key购买 nike

问题出在第 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),那么它就可以正常工作。

但是我需要传递参数。

如何解决这个问题?

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<T>和其他返回 Observable<HttpEvent<T>> 。如果返回值来自getHttpParamsany ,它认为您会得到后者。

因此,最小的修复是更具体地说明该方法可能返回的内容,例如:

protected getHttpParams(obj: object): {headers: HttpHeaders, params?: HttpParams} { ... }

关于javascript - 类型 'Observable<HttpEvent<T>>' 不可分配给类型 'Observable<T>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60972063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com