我正在尝试在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还是很陌生,因此在决定如何解决此问题时遇到了麻烦。任何建议,将不胜感激。
答案 0 :(得分:2)
我会这样
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))
)
您可以订阅,或使用模板中的异步管道