首页 > 解决方案 > 在 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)。我该怎么做?

标签: angularhttprequest

解决方案


@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));
  }

推荐阅读