首页 > 解决方案 > 如何将来自多个 HTTP 请求的 HTTPErrorResponse 对象存储在一个数组中?

问题描述

我正在尝试在我的 Angular 应用程序中构建一个 API 验证器。我有一个需要 GET 或 POST 的 URL 列表,并将任何 HTTP 错误存储在一个数组中,然后将显示在 UI 中。

我已经实施了以下服务来做到这一点:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { DataSource, ConfigValidationErrorObject } from './customTypes';

@Injectable()
export class ApiValidationService {
  apiValidationErrors: Array<ConfigValidationErrorObject> = new Array<ConfigValidationErrorObject>();

  constructor(
    private _httpClient: HttpClient,
  ) { }

  validate(dataSourceArray: Array<DataSource>): Array<ConfigValidationErrorObject> {
    dataSourceArray.map((url) => { this.validateApi(dataSource) });

    return this.apiValidationErrors;
  }

  validateApi(dataSource: DataSource) {
    if (dataSource.httpRequestType === 'GET') {
      this.executeGetRequest(dataSource.url, dataSource.options).subscribe(
        (data) => console.log(data),
        (error: HttpErrorResponse) => {
          this.addApiValidationError(error);
        }
      );
    }

    if (dataSource.httpRequestType === 'POST') {
      this.executePostRequest(dataSource.url, dataSource.body, dataSource.options).subscribe(
        (data) => console.log(data),
        (error: HttpErrorResponse) => {
          this.addApiValidationError(error);
        }
      );
    }
  }

  executeGetRequest(url: string, options: any) {
    return this._httpClient.get(url);
  }

  executePostRequest(url: string, body: any, options: any) {
    return this._httpClient.post(url, body, options);
  }

  addApiValidationError(httpErrorResponse: HttpErrorResponse) {
    const apiValidationError: ConfigValidationErrorObject = {
      message: httpErrorResponse.message,
    };

    this.apiValidationErrors.push(apiValidationError);
  }
}

当我validate()在组件中使用该方法时,我希望它返回的数组中填充我的自定义错误对象。但是我得到一个空数组,即使抛出错误(它们被正确记录到控制台)。我希望这是因为异步 HTTP 请求。

我正在阅读 Observables,但我不确定是否可以使用它们,因为我需要错误对象而不是 HTTP 请求返回的数据。我想知道我是否需要使用 Observables 或者我是否应该查看 Promises?如果我需要使用 Observables,任何人都可以帮我解决我的问题。

我对 Angular 很陌生,所以我很难决定如何解决这个问题。任何建议,将不胜感激。

标签: angularangular-httpclient

解决方案


我会这样

forkJoin(
  getCallOne()
    .pipe(map(() => null), catchError(error => {/* what you want to do here */})),
  getCallTwo()
    .pipe(map(() => null), catchError(error => {/* what you want to do here */})),
  postCallOne()
    .pipe(map(() => null), catchError(error => {/* what you want to do here */})),
  PostCallTwo()
    .pipe(map(() => null), catchError(error => {/* what you want to do here */})),
).pipe(
  map(errors => errors.filter(error => !!error))
)

然后你可以订阅它,或者在你的模板中使用异步管道

  • forkJoin创建一个 observables 数组并仅在所有调用完成时发出
  • 将答案映射为null因为您不会使用它(显然)
  • 使用catchError捕获错误并将其作为有效的 observable 返回
  • 映射最终错误以仅过滤错误(删除有效调用的值)

推荐阅读