typescript RequestOptions 迁移 Angular 5
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47585720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RequestOptions migration Angular 5
提问by Abner
I was using a custom request options in Angular 4 where I was doing the following:
我在 Angular 4 中使用自定义请求选项,我正在执行以下操作:
default-request-options.service.ts
默认请求选项.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
应用模块.ts
providers: [ // expose our Services and Providers into Angular's dependency injection
{ provide: RequestOptions, useClass: DefaultRequestOptions }
]
But after the migration notice that the RequestOption is not available in the new folder http/common/http
但是在迁移后通知RequestOption在新文件夹http/common/http中不可用
I'm would like to know if I still can use similar thing in Angular 5 or there is no point using it with the new HTTPClient? The main advantage for me was to set in one place only, not having to append it to all my requests.
我想知道我是否仍然可以在 Angular 5 中使用类似的东西,或者在新的 HTTPClient 中使用它没有意义?对我来说,主要优点是只在一个地方设置,不必将其附加到我的所有请求中。
I got the code initially in the angular docs: https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options.service.ts
我最初在 angular 文档中获得了代码:https: //github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options。服务.ts
采纳答案by hthserhs
You can use interceptorsto add default headers to your requests. Example from the 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);
}
}