如何将来自多个 HTTP 请求的 HTTPErrorResponse 对象存储在一个数组中?

How to store HTTPErrorResponse objects from multiple HTTP requests in an array?

我正在尝试在我的 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() 方法时,我希望数组 returns 填充我的自定义错误对象。但是我得到一个空数组,即使在抛出错误时(它们被正确地记录到控制台)。我希望这是因为异步 HTTP 请求。

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

我是 Angular 的新手,所以我无法决定如何解决这个问题。如有任何建议,我们将不胜感激。

我会这样走

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))
)

然后您可以订阅,或者在模板中使用async管道

  • forkJoin 创建一个 observable 数组,仅当所有调用完成时才发出
  • 将答案映射到 null 因为您不会使用它(显然)
  • 使用 catchError 来捕捉错误并且 return 它作为一个有效的 observable
  • map 最终错误只过滤错误(删除有效调用的null值)