Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 2, Http service wrapper to pass authorization token with each request.
import {Injectable, EventEmitter} from 'angular2/core';
import {Http, Headers, RequestOptions, RequestOptionsArgs, Response, RequestMethod, Request, Connection, ConnectionBackend} from 'angular2/http';
import * as Rx from 'rxjs';
export enum Action { QueryStart, QueryStop };
@Injectable()
export class AuthHttp {
process: EventEmitter<any> = new EventEmitter<any>();
authFailed: EventEmitter<any> = new EventEmitter<any>();
constructor(private _http: Http) { }
private _buildAuthHeader(): string {
return localStorage.getItem("authToken");
}
public get(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Get, url, null, options);
}
public post(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Post, url, body, options);
}
public put(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Put, url, body, options);
}
public delete(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Delete, url, null, options);
}
public patch(url: string, body: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Patch, url, body, options);
}
public head(url: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
return this._request(RequestMethod.Head, url, null, options);
}
private _request(method: RequestMethod, url: string, body?: string, options?: RequestOptionsArgs): Rx.Observable<Response> {
let requestOptions = new RequestOptions(Object.assign({
method: method,
url: url,
body: body
}, options));
if (!requestOptions.headers) {
requestOptions.headers = new Headers();
}
requestOptions.headers.set("Authorization", this._buildAuthHeader())
return Rx.Observable.create((observer) => {
this.process.next(Action.QueryStart);
this._http.request(new Request(requestOptions))
.map(res=> res.json())
.finally(() => {
this.process.next(Action.QueryStop);
})
.subscribe(
(res) => {
observer.next(res);
observer.complete();
},
(err) => {
switch (err.status) {
case 401:
//intercept 401
this.authFailed.next(err);
observer.error(err);
break;
default:
observer.error(err);
break;
}
})
})
}
}
@jkunz

This comment has been minimized.

Copy link

commented Feb 9, 2017

Thank you! thank you! You just saved me after hours of bashing my head against this, trying to figure out how to update my headers with an extension of Http

@prafful-garg

This comment has been minimized.

Copy link

commented Feb 13, 2017

how can i use this wrapper inside a component? i mean just in place of http.get should i use AuthHttp.get and it will work?

@harikrishnanp87

This comment has been minimized.

Copy link

commented Feb 21, 2017

@chandermani @jkunz How can i use this?

@EdenWooNz

This comment has been minimized.

Copy link

commented Apr 5, 2017

How to use it?

@amitagrawal11

This comment has been minimized.

Copy link

commented Apr 28, 2017

Hi thanks for sharing it with us, but how we will write logic to update/refresh expired token when we get 401 error.

@ajayullal

This comment has been minimized.

Copy link

commented May 4, 2017

Hi,
Thank you for sharing this code. I suggest you not to import the entire Rxjs library (import * as Rx from 'rxjs';) This will download about 200 scripts, instead download only those parts that you need.

Ex: import { Observable } from 'rxjs/Observable'; :)

@richard457

This comment has been minimized.

Copy link

commented Jun 3, 2017

Please how to use it?

@gschambial

This comment has been minimized.

Copy link

commented Jul 31, 2017

Thanks a lot :) I am new to angular and was implementing login. Saved a lot of effort.

@najibla

This comment has been minimized.

Copy link

commented Oct 30, 2017

Why would you have to override all the http methods (get, post, delete..) when you can just override the request method ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.