使用HttpClient时,我在返回类型上遇到编译错误。在我的函数GetPortfolio
中,我希望GET
调用返回Observable<Portfolio>
类型的json对象,但它会给出错误:
类型Observable<HttpEvent<Portfolio>>
不能分配给Observable<Portfolio>
类型。类型HttpEvent<Portfolio>
不能分配Portfolio
类型。类型HttpProgressEvent
不能分配Portfolio
类型。类型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);
}
}
从角度英雄教程和文档中,HttpClient请求应该是Observable<any>
:Angular HttpClient doc
我做错了什么?或者我应该将返回值设置为Observable<HttpEvent<Portfolio>>
?
答案 0 :(得分:21)
Typecast你的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>;
答案 1 :(得分:7)
很奇怪,如果你写的话,不要给出错误
/glassfish/glassfish4/lib/
看起来,编译器期望一个带有标题,params,observe ...的对象,但是由于你的对象没有类型,编译器可以接受它
即使你可以做到
GetPortfolio(portfolioId: string): Observable<Portfolio> {
return this.http.get<Portfolio>('....', {
headers: new HttpHeaders(
{
'Content-Type': 'application/json',
})
});
}
答案 2 :(得分:2)
我解决了这样的转换标题参数的问题
return this.http.get<SomeModel>(someUrl, <Object>this.options);
答案 3 :(得分:1)
正如各种答案所提到的,简而言之:
您的选项必须是 object
类型而不是 any
类型
答案 4 :(得分:0)
因为这是一项服务&#39; PortfolioService&#39;我们可能不需要这里的接口,而是我们可以使用类型any,而且这里只需要GET方法。
GetPortfolio(portfolioId): Observable<any> {
return this.http.get(this.apiUrl + '/${portfolioId}')
.map((response:any) => {
return response;
});
}
这应该有效,请尝试。