Angular在用户登录后设置授权请求头headers.append('Authorization', 'token');
方案1. 使用Angular http
import {Injectable} from '@angular/core'; import {Http, Headers} from '@angular/http'; @Injectable() export class HttpClient { constructor(private http: Http) {} createAuthorizationHeader(headers: Headers) { headers.append('Authorization', 'Basic ' + btoa('username:password')); } get(url) { let headers = new Headers(); this.createAuthorizationHeader(headers); return this.http.get(url, { headers: headers }); } post(url, data) { let headers = new Headers(); this.createAuthorizationHeader(headers); return this.http.post(url, data, { headers: headers }); } }
方案2.Angular 4.3.x及更高版本可以执行如下操作来添加请求头
2.1拦截器设置
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, } from '@angular/common/http'; export class AddHeaderInterceptor implements HttpInterceptor { intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // Clone the request to add the new header const clonedRequest = req.clone({ headers: req.headers.set('Authorization', 'Bearer 123') }); // Pass the cloned request instead of the original request to the next handle return next.handle(clonedRequest); } }
2.2创建拦截器后,您应该使用HTTP_INTERCEPTORS
提供的注册。
import { HTTP_INTERCEPTORS } from '@angular/common/http'; @NgModule({ providers: [{ provide: HTTP_INTERCEPTORS, useClass: AddHeaderInterceptor, multi: true, }], }) export class AppModule {}
方案3.配置扩展BaseRequestOptions
3.1配置代码如下
import {provide} from 'angular2/core'; import {bootstrap} from 'angular2/platform/browser'; import {HTTP_PROVIDERS, Headers, Http, BaseRequestOptions} from 'angular2/http'; import {AppCmp} from './components/app/app'; class MyRequestOptions extends BaseRequestOptions { constructor () { super(); this.headers.append('My-Custom-Header','MyCustomHeaderValue'); } } bootstrap(AppCmp, [ ROUTER_PROVIDERS, HTTP_PROVIDERS, provide(RequestOptions, { useClass: MyRequestOptions }) ]);
3.2添加请求头
this.http._defaultOptions.headers.append('Authorization', 'token'); 或者 this.http._defaultOptions.headers.set('Authorization', 'token');
3.3删除请求头
this.http._defaultOptions.headers.delete('Authorization');
参考来源:https://www.itranslater.com/qa/details/2112366855208829952