有一个库允许您将 HttpClient 与强类型回调一起使用。
数据和错误可直接通过这些回调获得。
当您将 HttpClient 与 Observable 一起使用时,您必须在其余代码中使用 .subscribe(x=>...)。
这是因为 ObservableHttpResponseT>> 与 HttpResponse 绑定。
这将http层与您的代码的其余部分紧密结合。
这个库封装了 .subscribe(x => ...) 部分,只通过你的模型暴露数据和错误。
使用强类型回调,您只需在其余代码中处理模型。
该库名为 angular-extended-http-client。
angular-extended-http-client library on GitHub
angular-extended-http-client library on NPM
非常容易使用。
示例用法
强类型回调是
成功:
- IObservableT>
- IObservableHttpResponse
- IObservableHttpCustomResponseT>
失败:
- IObservableErrorTError>
- IObservableHttpError
- IObservableHttpCustomErrorTError>
将包添加到您的项目和应用模块中
import { HttpClientExtModule } from 'angular-extended-http-client';
在@NgModule 导入中
imports: [
.
.
.
HttpClientExtModule
],
你的模型
//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 { 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.
getRaceInfo(success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
let url = this.config.apiEndpoint;
this.client.get(url, ResponseType.IObservable, success, ErrorType.IObservableError, failure);
}
}
你的组件
在您的组件中,您的服务被注入并调用 getRaceInfo API,如下所示。
ngOnInit() {
this.service.getRaceInfo(response => this.result = response.result,
error => this.errorMsg = error.className);
}
回调中返回的 response 和 error 都是强类型的。例如。 response 是 RacingResponse 类型,error 是 APIException。
您只在这些强类型回调中处理您的模型。
因此,您的其余代码只知道您的模型。
另外,您仍然可以使用传统路由并从 Service API 返回 ObservableHttpResponse<T>>。