gpt4 book ai didi

Angular HttpClient 返回期望 observable 而不是 observable

转载 作者:太空狗 更新时间:2023-10-29 16:57:54 25 4
gpt4 key购买 nike

我在使用 HttpClient 时遇到有关返回类型的编译错误。在我的函数中 GetPortfolio , 我期待 GET调用返回 Observable<Portfolio> 类型的 json 对象但它给出了错误:

输入 Observable<HttpEvent<Portfolio>>不可分配给类型 Observable<Portfolio> .输入 HttpEvent<Portfolio>不可分配给类型 Portfolio .输入 HttpProgressEvent不可分配给类型 Portfolio .属性(property)name缺少类型 HttpProgressEvent .

我的代码:

import { Injectable } from '@angular/core';
import { environment } from './environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';


export interface Portfolio {
name: string;
id: string;
}

@Injectable()
export class PortfolioService {

private httpOptions;

apiUrl: string;

constructor(private http: HttpClient) {
this.apiUrl = environment.apiUrl + "/api/portfolios";

this.httpOptions = {
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
})
};
}


GetPortfolio(portfolioId: string): Observable<Portfolio> {
return this.http.get<Portfolio>(this.apiUrl + '/${portfolioId}', this.httpOptions);
}

}

来自 angular hero 教程和文档 HttpClient 请求应该期待 Observable<any> : Angular HttpClient doc

那我是不是做错了什么?或者我应该将返回值设置为 Observable<HttpEvent<Portfolio>>

最佳答案

强制转换您的 httpOptions

private httpOptions: {
headers: HttpHeaders
};

typescript 编译器提取了错误的 get 方法类型 ( src )

/**
* Construct a GET request which interprets the body as JSON and returns the full event stream.
*
* @return an `Observable` of all `HttpEvent`s for the request, with a body type of `T`.
*/
get<T>(url: string, options: {
headers?: HttpHeaders | {[header: string]: string | string[]},
observe: 'events',
params?: HttpParams|{[param: string]: string | string[]},
reportProgress?: boolean,
responseType?: 'json',
withCredentials?: boolean,
}): Observable<HttpEvent<T>>;

当您指定带有标题的类型时,它会提取正确的类型。 ( src )

/**
* Construct a GET request which interprets the body as JSON and returns it.
*
* @return an `Observable` of the body as type `T`.
*/
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>;

关于Angular HttpClient 返回期望 observable<HttpEvent<any> 而不是 observable<any>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48401250/

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