我需要在用户登录后为每个后续请求设置一些授权 header 。
为特定请求设置 header ,
import {Headers} from 'angular2/http';
var headers = new Headers();
headers.append(headerName, value);
// HTTP POST using these headers
this.http.post(url, data, {
headers: headers
})
// do something with the response
但是这种方式手动为每个请求设置请求头是不可行的。
如何在用户登录后设置 header 集,并在注销时删除这些 header ?
最佳答案
要回答这个问题,您质疑您是否可以提供一种服务来包装来自 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
});
}
}
您可以注入(inject)这个对象 (HttpClient
),而不是注入(inject) Http
对象。
import { HttpClient } from './http-client';
export class MyComponent {
// Notice we inject "our" HttpClient here, naming it Http so it's easier
constructor(http: HttpClient) {
this.http = httpClient;
}
handleSomething() {
this.http.post(url, data).subscribe(result => {
// console.log( result );
});
}
}
我还认为,通过提供您自己的扩展 Http
类的类,可以为 Http
类使用多个提供程序来完成某些事情...请参阅此链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html。
关于Angular - 为每个请求设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464108/