angular - 在 Angular 中使用自定义 http 请求时,如何禁用 'sent' event.type?
问题描述
当我在 Angular (7) 中使用未预定义的 http 请求时,我的订阅正文中收到了 2 次响应,但如果我使用 GET 等预定义的 http 请求,则只有 1 个响应。
服务中的自定义请求 (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)。我该怎么做?
解决方案
@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));
}
推荐阅读
- postgresql - postgraphile - 将结构化数据添加为突变字段的功能
- visual-studio-code - vscode中是否有用于文件比较的API
- javascript - 单击链接不会触发或不会触发导航
- bloomberg - 有没有人使用 Blpapi/Pdblp 等软件包从 Bloomberg 导出供应链数据 (SPLC)?
- css - 表格行边框重叠外部表格边框
- java - JButton 没有放置在正确的位置或正在消失
- c# - 组合框的 SelectedIndex 值从设计器中消失
- mysql - 如何将 Angular 9 中的 JSON 数组以多对多关系放置到后端(Spring Boot)?
- firefox - Ubuntu 上的 Firefox:网络监视器选择多个请求
- javascript - Bootstrap-table2 如何在字符串月份和日期上进行自定义文本搜索过滤器?