我在 Angular 4 中使用自定义请求选项,我正在执行以下操作:
默认请求选项.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 一起使用是没有意义的?对我来说,主要优势是只在一个地方设置,而不必将其附加到我的所有请求中。
我最初在 Angular 文档中获得了代码:https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options.service.ts
最佳答案
您可以使用 interceptors为您的请求添加默认 header 。来自 Angular 文档的示例:
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);
}
}
关于angular - RequestOptions 迁移 Angular 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47585720/