Interceptors in Angular2

后端 未结 3 771
说谎
说谎 2020-12-15 07:32

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 s

3条回答
  •  無奈伤痛
    2020-12-15 07:49

    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
    
    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',  {
        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.

提交回复
热议问题