Abn*_*ner 12 typescript angular
我在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;
}
}
Run Code Online (Sandbox Code Playgroud)
App.Module.ts
providers: [ // expose our Services and Providers into Angular's dependency injection
{ provide: RequestOptions, useClass: DefaultRequestOptions }
]
Run Code Online (Sandbox Code Playgroud)
但是在迁移通知之后,新文件夹http/common/http中的RequestOption不可用
我想知道我是否仍然可以在Angular 5中使用类似的东西,或者使用新的HTTPClient没有意义吗?对我来说,主要的优点是只设置在一个地方,而不必将其附加到我的所有要求.
我最初在angular docs中得到了代码:https://github.com/angular/angular.io/blob/master/public/docs/_examples/server-communication/ts/src/app/default-request-options. service.ts
Nis*_*hth 11
您可以使用拦截器为您的请求添加默认标头.角度文档的示例:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
9873 次 |
最近记录: |