Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interceptors in Angular2

Tags:

angular

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.

like image 263
codin Avatar asked Dec 18 '15 12:12

codin


People also ask

Why interceptors are used?

What Are Interceptors? Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient . They can handle both HttpRequest as well as HttpResponse .

What are the interceptors in angular?

The angular interceptor is a medium connecting the backend and front-end applications. Whenever a request is made, the interceptors handle it in between. They can also identify the response by performing Rxjs operators. The interceptors do not initiate the handle method and handle the requests at their level.

What is interceptor explain with example?

Interceptors are a unique type of Angular Service that we can implement. Interceptors allow us to intercept incoming or outgoing HTTP requests using the HttpClient . By intercepting the HTTP request, we can modify or change the value of the request.

Can we have multiple interceptors?

Setting multi to true, makes sure that you can have multiple interceptors in your project. Now we create interceptor. ts in /src/app and since interceptors are services we need to use @Injectable() decorator in our file: Keep in mind that Interceptors are Services.


2 Answers

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.

like image 77
wendro Avatar answered Oct 07 '22 00:10

wendro


first in app.module.ts add following line at providers array:

    {provide : Http, useFactory: (xhrBackend: XHRBackend, requestOptions:  RequestOptions) => new HttpInterceptor(xhrBackend, requestOptions),deps:  [XHRBackend, RequestOptions]}

Create HttpIntreceptor file with

    import {Http, RequestOptionsArgs, RequestOptions, Response, Request, ConnectionBackend} from "@angular/http";
    import {Observable} from "rxjs/Observable";
    import "rxjs/add/operator/catch"; 
    import "rxjs/add/observable/throw";
    import "rxjs/add/observable/empty";
    import {Router} from "@angular/router";

    export class HttpInterceptor extends Http {
        constructor(backend: ConnectionBackend, defaultOptions: RequestOptions,    private _router: Router) {
            super(backend, defaultOptions);
        }

        request(url: string | Request, options?: RequestOptionsArgs):      Observable<Response> {
            return this.intercept(super.request(url, options));
        }

        get(url: string, options?: RequestOptionsArgs): Observable<Response> {
            return this.intercept(super.get(url,options));
        }

        post(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
            return this.intercept(super.post(url, body, options));
        }

        put(url: string, body: string, options?: RequestOptionsArgs): Observable<Response> {
            return this.intercept(super.put(url, body, options));
        }

        delete(url: string, options?: RequestOptionsArgs): Observable<Response> {
            return this.intercept(super.delete(url, options));
        }

        intercept(observable: Observable<Response>): Observable<Response> {
            return observable.catch((err, source) => {
            });
        }
    }
like image 26
Yoav Schniederman Avatar answered Oct 07 '22 00:10

Yoav Schniederman