angular - 如何将来自多个 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 很陌生,所以我很难决定如何解决这个问题。任何建议,将不胜感激。
解决方案
我会这样
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 返回
- 映射最终错误以仅过滤错误(删除有效调用的空值)
推荐阅读
- ionic3 - ngx-mqtt TypeError: __WEBPACK_IMPORTED_MODULE_0__angular_core__.defineInjectable 不是函数
- ionic-framework - 在离子 4 中解散后打开加载
- php - 缓存 SQL 查找和检索数据
- html - 尝试将鼠标悬停在页脚菜单上时它会消失
- python - 在 Python 中实现多图
- python-3.x - Find the average of a value in a list of tuples within a list of dictionaries in Python
- vue.js - 我可以将 Laravel 与 Vue 店面模板混合使用吗
- java - 构造函数中的布尔值设置为 true
- angular - Angular 2 - 我的子路线没有打开任何东西
- swift - 在 Heroku 上使用 Vapor 3 配置 PostgreSQL 数据库