Angular HttpClient 返回期望 observable<HttpEvent<any>而不是 observable<any> [英] Angular HttpClient return expecting observable<HttpEvent<any> rather than observable<any>
问题描述
我在使用 HttpClient 时在返回类型上遇到编译错误.在我的函数 GetPortfolio
中,我期望 GET
调用返回 Observable
类型的 json 对象,但它给出了错误:
I'm getting a compilation error on the return type when using HttpClient. In my function GetPortfolio
, I'm expecting the GET
call to return the json object of type Observable<Portfolio>
but it's giving the error:
类型 Observable
不可分配给类型 Observable
.类型 HttpEvent
不可分配给类型 Portfolio
.类型 HttpProgressEvent
不可分配给类型 Portfolio
.HttpProgressEvent
类型中缺少属性 name
.
Type Observable<HttpEvent<Portfolio>>
is not assignable to type Observable<Portfolio>
. Type HttpEvent<Portfolio>
is not assignable to type Portfolio
. Type HttpProgressEvent
is not assignable to type Portfolio
. Property name
is missing in type 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
: Angular HttpClient 文档
From the angular hero tutorial and docs HttpClient requests should expect Observable<any>
: Angular HttpClient doc
所以我做错了什么吗?或者我应该将返回值设置为 Observable
?
So am I doing something wrong? Or should I be setting the return value to Observable<HttpEvent<Portfolio>>
?
推荐答案
奇怪了,写了别报错
GetPortfolio(portfolioId: string): Observable<Portfolio> {
return this.http.get<Portfolio>('....', {
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
})
});
}
看起来,编译器期望一个带有properites headers,params,observe...的对象,但是由于您的对象没有类型,编译器可以接受它
It's look like, the compiler expect an object with the properites headers,params,observe..., but as your object have no type, the compiler can accept it
你也能做到
headers: HttpHeaders = new HttpHeaders({
'Content-Type': 'application/json',
})
GetPortfolio(portfolioId: string): Observable<Portfolio> {
return this.http.get<Portfolio>('...', {
headers: this.headers
})
}
这篇关于Angular HttpClient 返回期望 observable<HttpEvent<any>而不是 observable<any>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!