我需要在用户登录后为每个后续请求设置一些授权标头。
信息:
要为特定请求设置标头,
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
但是以这种方式为每个请求手动设置请求头是不可行的。
HTTP拦截器在Angular 2中不支持,但在Angular Github:
https://github.com/angular/angular/issues/2684中有一个有趣的讨论。
原文链接:https://www.f2er.com/angularjs/147038.html回答,你的问题,你可以提供一个服务,包装来自Angular2的原始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,{ headers: headers }); } }
而不是注入Http对象,你可以注入这一个(HttpClient)。
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 ); }); } }
我也认为可以做一些事情可以使用mult提供程序为Http类提供您自己的类扩展Http一个…查看此链接:http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html。
希望它帮助你,Thierry