我喜欢覆盖默认选项的想法,这似乎是一个很好的解决方案。
但是,如果您打算扩展Http类。一定要把这篇文章看完!
这里的一些答案实际上显示了request()方法的不正确重载,这可能导致难以捕捉的错误和奇怪的行为。这是我自己偶然发现的。
这个解决方案基于Angular 4.2中的request()方法实现。X,但应该是未来兼容的:
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {
ConnectionBackend, Headers,
Http as NgHttp,
Request,
RequestOptions,
RequestOptionsArgs,
Response,
XHRBackend
} from '@angular/http';
import {AuthenticationStateService} from '../authentication/authentication-state.service';
@Injectable()
export class Http extends NgHttp {
constructor (
backend: ConnectionBackend,
defaultOptions: RequestOptions,
private authenticationStateService: AuthenticationStateService
) {
super(backend, defaultOptions);
}
request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
if ('string' === typeof url) {
url = this.rewriteUrl(url);
options = (options || new RequestOptions());
options.headers = this.updateHeaders(options.headers);
return super.request(url, options);
} else if (url instanceof Request) {
const request = url;
request.url = this.rewriteUrl(request.url);
request.headers = this.updateHeaders(request.headers);
return super.request(request);
} else {
throw new Error('First argument must be a url string or Request instance');
}
}
private rewriteUrl (url: string) {
return environment.backendBaseUrl + url;
}
private updateHeaders (headers?: Headers) {
headers = headers || new Headers();
// Authenticating the request.
if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
}
return headers;
}
}
注意,我是这样导入原始类的:import {Http as NgHttp} from '@angular/ Http ';为了防止名字冲突。
这里要解决的问题是request()方法有两个不同的调用签名。当传递的是Request对象而不是URL字符串时,Angular会忽略options参数。所以这两种情况都必须妥善处理。
下面是如何用DI容器注册这个被重写的类的例子:
export const httpProvider = {
provide: NgHttp,
useFactory: httpFactory,
deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};
export function httpFactory (
xhrBackend: XHRBackend,
requestOptions: RequestOptions,
authenticationStateService: AuthenticationStateService
): Http {
return new Http(
xhrBackend,
requestOptions,
authenticationStateService
);
}
使用这种方法,您可以正常地注入Http类,但您的重写类将被神奇地注入。这允许您轻松地集成您的解决方案,而无需更改应用程序的其他部分(操作中的多态性)。
只需将httpProvider添加到模块元数据的providers属性中。