我需要在用户登录后为每个后续请求设置一些授权标头.
要为特定请求设置标头,
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
Run Code Online (Sandbox Code Playgroud)
但是以这种方式为每个请求手动设置请求标头是不可行的.
如何在用户登录后设置标头集,并在注销时删除这些标头?
由于我已经开始使用angular2,我已经设置了我的服务来返回T的Observable.在服务中我会有map()调用,使用这些服务的组件只会使用subscribe()来等待响应.对于这些简单的场景我真的不需要深入研究rxjs所以一切都还可以.
我现在想要实现以下目标:我正在使用Oauth2身份验证和刷新令牌.我想构建一个所有其他服务都将使用的api服务,并在返回401错误时透明地处理刷新令牌.因此,在401的情况下,我首先从OAuth2端点获取新令牌,然后使用新令牌重试我的请求.下面的代码工作正常,承诺:
request(url: string, request: RequestOptionsArgs): Promise<Response> {
var me = this;
request.headers = request.headers || new Headers();
var isSecureCall: boolean = true; //url.toLowerCase().startsWith('https://');
if (isSecureCall === true) {
me.authService.setAuthorizationHeader(request.headers);
}
request.headers.append('Content-Type', 'application/json');
request.headers.append('Accept', 'application/json');
return this.http.request(url, request).toPromise()
.catch(initialError => {
if (initialError && initialError.status === 401 && isSecureCall === true) {
// token might be expired, try to refresh token.
return me.authService.refreshAuthentication().then((authenticationResult:AuthenticationResult) => {
if (authenticationResult.IsAuthenticated == true) {
// retry with new token
me.authService.setAuthorizationHeader(request.headers);
return this.http.request(url, request).toPromise();
} …Run Code Online (Sandbox Code Playgroud)