当我在Angular(7)中使用未预定义的http请求时,我在订阅正文中得到了2次响应,但是如果我使用像GET这样的预定义http请求,则只有1个响应。 / p>
服务中的自定义请求(SEARCH):
searchFileByCategory(categories: Array<string>): Observable<any> {
return this.http.request(new HttpRequest('SEARCH', ENDPOINTS.SEARCH_FILE_BY_CATEGORY, {categories: categories}));
}
在组件中:
refreshTable(): void {
this.backEndService.searchFileByCategory(this.categories).subscribe(event => {
console.log(event);
if (event.type === HttpEventType.Response) {
this.files = event.body.data;
}
});
}
第一个事件日志:
{type: 0}
第二个事件日志:
{body: {data: {…}}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
ok: true
status: 200
statusText: "OK"
type: 4
url: "http://localhost/..."}
如您所见,我必须检查( event.type === HttpEventType.Response ),因为 event.body.data 在第一个响应中不存在
node_modules @ angular \ common \ http \ src \ response.d.ts中的HttpEventType枚举:
export declare enum HttpEventType {
/**
* The request was sent out over the wire.
*/
Sent = 0,
/**
* An upload progress event was received.
*/
UploadProgress = 1,
/**
* The response status code and headers were received.
*/
ResponseHeader = 2,
/**
* A download progress event was received.
*/
DownloadProgress = 3,
/**
* The full response including the body was received.
*/
Response = 4,
/**
* A custom event from an interceptor or a backend.
*/
User = 5
}
我已经知道第一个反应是什么。但是我不明白GET为何没有相同的原因。
服务中的GET请求:
getZipCodes(): Observable<any> {
return this.http.get(ENDPOINTS.GET_ZIP_CODES);
}
在组件中:
refreshZipCodes(): void {
this.backEndService.getZipCodes().subscribe(response => this.zipCodes = response.data)
}
此处无需检查(event.type === HttpEventType.Response)。为什么?
我的最终目的是在每次调用自定义http请求时摆脱检查(event.type === HttpEventType.Response)。我该怎么办?
答案 0 :(得分:0)
@ABOS在该帖子下的答案看起来不错,它的工作原理是:
searchLastContentByCategory(category: string): Observable<any> {
return this.http.request(new HttpRequest('SEARCH', ENDPOINTS.SEARCH_LAST_CONTENT_BY_CATEGORY, {category: category}))
.pipe(filter((event: HttpEvent<any>) => event instanceof HttpResponse));
}