使用HttpClient时,我在返回类型上遇到编译错误.在我的函数GetPortfolio中,我期待GET调用返回Observable类型的json对象< Portfolio>但它给出了错误:
输入Observable< HttpEvent< Portfolio>>不能分配给Observable< Portfolio>类型.输入HttpEvent< Portfolio>不能分配给类型投资组合.类型HttpProgressEvent不能分配给类型Portfolio. 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>> ?
这很奇怪,如果你写的话不要给错误
GetPortfolio(portfolioId: string): Observable<Portfolio> { return this.http.get<Portfolio>('....',{ headers: new HttpHeaders( { 'Content-Type': 'application/json',}) }); }
看起来,编译器期望一个对象具有正确的头,参数,观察……,但由于你的对象没有类型,编译器可以接受它
即使你能做到
headers: HttpHeaders = new HttpHeaders({ 'Content-Type': 'application/json',}) GetPortfolio(portfolioId: string): Observable<Portfolio> { return this.http.get<Portfolio>('...',{ headers: this.headers }) }