您可以使用一个库进行发布/获取,该库允许您将 HttpClient 与强类型回调一起使用。
数据和错误可直接通过这些回调获得。
该库名为 angular-extended-http-client。
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
非常容易使用。
传统方法
在传统方法中,您从 Service API 返回 ObservableHttpResponse<T>>。这与 HttpResponse 相关。
使用这种方法,您必须在其余代码中使用 .subscribe(x => ...)。
这会在 http 层 和 您的代码的其余部分 之间创建紧密耦合。
强类型回调方法
您只在这些强类型回调中处理您的模型。
因此,您的其余代码只知道您的模型。
示例用法
强类型回调是
成功:
- IObservableT>
- IObservableHttpResponse
- IObservableHttpCustomResponseT>
失败:
- IObservableErrorTError>
- IObservableHttpError
- IObservableHttpCustomErrorTError>
将包添加到您的项目和应用模块中
import { HttpClientExtModule } from 'angular-extended-http-client';
在@NgModule 导入中
imports: [
.
.
.
HttpClientExtModule
],
你的模型
export class SearchModel {
code: string;
}
//Normal response returned by the API.
export class RacingResponse {
result: RacingItem[];
}
//Custom exception thrown by the API.
export class APIException {
className: string;
}
您的服务
在您的服务中,您只需使用这些回调类型创建参数。
然后,将它们传递给 HttpClientExt 的 get 方法。
import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.
@Injectable()
export class RacingService {
//Inject HttpClientExt component.
constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {
}
//Declare params of type IObservable<T> and IObservableError<TError>.
//These are the success and failure callbacks.
//The success callback will return the response objects returned by the underlying HttpClient call.
//The failure callback will return the error objects returned by the underlying HttpClient call.
searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.post<SearchModel, RacingResponse>(url, model,
ResponseType.IObservable, success,
ErrorType.IObservableError, failure);
}
}
你的组件
在您的组件中,注入您的服务并调用 searchRaceInfo API,如下所示。
search() {
this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
error => this.errorMsg = error.className);
}
回调中返回的 response 和 error 都是强类型的。例如。 response 是 RacingResponse 类型,error 是 APIException。