在Angular2拦截 [英] Interceptors in Angular2
问题描述
我想建立一个演示应用程序的 Angular2.beta.0 这将对登录机制,然后所有其他的API调用将不得不通过标题发出的收购会话令牌。
I am trying to build a demo app on Angular2.beta.0 which would have login mechanism and then all the other API calls would have the acquired session token sent via the headers.
在角1个,我可以写一个拦截这将令牌添加到HTTP标头在一个单独的code,我想知道,如果angular2有这样一种机制,或做任何其它的推荐方式。
In angular 1x, I could write an Interceptor which would add the token to the http header in a separate code, I would like to know if angular2 has such kind of mechanism or any other recommended way to do this.
推荐答案
必须是HTTP请求的头?饼干似乎是一个不错的选择:
的https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
Has to be HTTP header of the requests? Cookies seems to be a good choice: https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage/
通过查看 HTTP 文档,我们有:
By looking at HTTP documentation we have:
get(url: string, options?: RequestOptionsArgs) : Observable<Response>
Performs a request with get http method.
将 RequestOptionsArgs 我们有:
headers : Headers
Not Yet Documented
最后降落在头。
import {Headers} from 'angular2/http';
var secondHeaders = new Headers({
'X-My-Custom-Header': 'Angular'
});
因此,它应该是这样的:
So it should be something like:
import {Response} from "angular2/http";
import {RequestOptionsArgs} from "angular2/http";
import {Headers} from "angular2/http";
let token:string = 'my-secret';
this.http.get('your/url', <RequestOptionsArgs> {
headers: new Headers({
'X-My-JWT-Header': 'sweet'
})
})
看着 BaseRequestOptions 文档,这是一种方式这个头连接到自动方式每个请求。
Looking at BaseRequestOptions documentation this is a way to attach this header to each request in automatic way.
这篇关于在Angular2拦截的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!