我在Angular 4中使用了自定义请求选项,我正在执行以下操作:
默认请求-options.service.ts
@Injectable()
export class DefaultRequestOptions extends BaseRequestOptions {
headers = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
});
merge(options?: RequestOptionsArgs): RequestOptions {
var newOptions = super.merge(options);
const token: string = localStorage.getItem('token');
if (token) {
newOptions.headers.set('token', token);
}
return newOptions;
}
}
App.Module.ts
providers: [ // expose our Services and Providers into Angular's dependency injection
{ provide: RequestOptions, useClass: DefaultRequestOptions }
]
但是在迁移通知之后,新文件夹http / common / http
中的RequestOption不可用我想知道我是否仍然可以在Angular 5中使用类似的东西,或者使用新的HTTPClient没有意义?对我来说,主要的优点是只设置在一个地方,而不必将其附加到我的所有请求中。
答案 0 :(得分:9)
您可以使用interceptors为您的请求添加默认标头。来自angular docs的示例:
import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private auth: AuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// Get the auth header from the service.
const authHeader = this.auth.getAuthorizationHeader();
// Clone the request to add the new header.
const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)});
// Pass on the cloned request instead of the original request.
return next.handle(authReq);
}
}