Angular2 - 设置头为每个请求 [英] Angular2 - set headers for every request
问题描述
我需要设置一些标题授权用户登录后,以后每请求。
I need to set some Authorization headers after the user has logged in, for every subsequent request.
简介:
要为特定的请求设置头,
To set headers for a particular request,
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
但它会不会是手动设置请求头以这种方式每个请求是可行的。
But it would be not be feasible to manually set request headers for every request in this way.
如何设置,一旦用户登录设置的标头,并且还删除对注销这些头?
How do I set the headers set once the user has logged in, and also remove those headers on logout?
推荐答案
HTTP拦截器不角2的支持,但有关于这个问题的角度Github上一个有趣的讨论:<一href=\"https://github.com/angular/angular/issues/2684\">https://github.com/angular/angular/issues/2684.
HTTP interceptors aren't supported in Angular 2 but there is an interesting discussion on this subject in the Angular Github: https://github.com/angular/angular/issues/2684.
要回答你的问题,你可以提供一个包装从Angular2原始 HTTP
对象的服务。喜欢的东西如下所述。
To answer, you question you could provide a service that wraps the original Http
object from Angular2. Something like described below.
import {Http, Headers) from 'angular2/http';
@Injectable()
export class HttpClient {
constructor(http: Http) {
this.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
});
}
}
和,而不是注入Http对象,你可以注入这一项。
And instead of injecting the Http object you could inject this one.
import {HttpClient} from './http-client';
export classMyComponent {
constructor(httpClient: HttpClient) {
this.httpClient = httpClient;
}
handleSomething() {
this.httpClient.post(url, data)
).subscribe(...);
}
}
我也觉得这事可以使用为 HTTP
类MULT提供商通过提供扩展自己的类的 HTTP $ C $完成ç>一...查看此链接:<一个href=\"http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html\">http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.
I also think that something could be done using mult providers for the Http
class by providing your own class extending the Http
one... See this link: http://blog.thoughtram.io/angular2/2015/11/23/multi-providers-in-angular-2.html.
希望它可以帮助你,
蒂埃里
Hope it helps you, Thierry
这篇关于Angular2 - 设置头为每个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!