Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
831 views
in Technique[技术] by (71.8m points)

angular - Interceptors in Angular2

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/

By looking at HTTP documentation we have:

get(url: string, options?: RequestOptionsArgs) : Observable<Response>

Performs a request with get http method.

Going to RequestOptionsArgs we have:

headers : Headers

Not Yet Documented

Finally landing at Headers.

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'
    })
})

Looking at BaseRequestOptions documentation this is a way to attach this header to each request in automatic way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...