这个问题在这里已有答案:
我正在尝试使用@ angular / common / http中的Angular 4和HttpClient / HttpHeaders来发出HTTP GET请求。以下是我的请求:
getPhysicians() {
let queryURL, queryOptions;
queryURL = "http://path/to/our/backend/pathologists";
queryOptions = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
withCredentials: true
};
let request = this.http.get<any[]>(queryURL, queryOptions);
request.subscribe(
data => {
data.forEach((physician) => { // no problems here
// some logic with the response items
})
},
err => {
console.log("Error retrieving physicians");
}
);
}
这段代码工作正常。但是,我和我的合作伙伴已经决定我们不需要在每个组件中包含一些此类信息,并决定构建查询构建服务。这是看起来像:
import { Injectable } from '@angular/core';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class QueryBuilderService {
baseURL: string = "http://path/to/our/backend/"
requestOptions: any = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded'),
withCredentials: true
};
constructor() { }
getRequestOptions() {
return this.requestOptions;
}
getAllPhysiciansQuery() {
return this.baseURL + "pathologists";
}
}
注入服务的组件中调整后的代码如下所示:
getPhysicians() {
let queryURL, queryOptions;
queryURL = this.queryBuilderService.getAllPhysiciansQuery();
queryOptions = this.queryBuilderService.getRequestOptions();
let request = this.http.get<any[]>(queryURL, queryOptions);
request.subscribe(
data => {
data.forEach((physician) => { // this line now throws a compilation error
// some logic with the response items
})
},
err => {
console.log("Error retrieving physicians");
}
);
}
我们返回与以前相同的确切值,但现在从此服务返回。但是,我们现在在“data”函数参数上声明了TypeScript错误
Property 'forEach' does not exist on type 'HttpEvent<any[]>'.
Property 'forEach' does not exist on type 'HttpSentEvent'.
我不能为我的生活弄清楚为什么我们得到一个错误,如果我们返回相同的确切值。为什么类型不再像任何[]那样回归?我已经验证了queryURL参数是否有效,无论它是在getPhysicians中创建还是从QueryBuilderService中提取。这是导致此类型问题的选项。
编辑以下是我们以原始方式进行调用时返回的内容:注意,这只是测试数据。这里没有真正的敏感信息。
任何帮助是极大的赞赏
好吧,多亏了@GreyBeardedGeek,我找到了我的解决方案。我需要向getRequestOptions()函数显式声明一个Object的返回类型。本质上,如果不明确知道函数返回一种Object类型,它将默认为HttpEvent类型。可在此链接中找到更多信息:
Property 'data' does not exist on type 'HttpEvent<Customer>'
从HttpClient的文档:
responseType
值确定如何解析成功的响应主体。如果responseType
是默认的json
,则结果对象的类型接口可以作为类型参数传递给request()
。
老实说,我不确定你的第一次和第二次尝试之间会发生什么变化会破坏它,但你会得到HttpEvent
作为回应。您可以通过以下几种方式更改此设置:
responseType: 'json'
添加到requestOptionsobserve: 'body'
添加到requestOptions.subscribe
回调以处理HttpEvent,例如request.subscribe((event: HttpEvent) => {
if (event.type === HttpEventType.response) {
event.body.forEach(physician => { /* logic */ });
}
},
根据其他评论和答案,您还应该使用requestOptions: Object
而不是requestOptions: any
和/或更新getRequestOptions
来返回Object
的类型。