Skip to content

Instantly share code, notes, and snippets.

@andela-kakpobome
Created January 16, 2018 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andela-kakpobome/bf0e3ff860e66631df8c154cbb606247 to your computer and use it in GitHub Desktop.
Save andela-kakpobome/bf0e3ff860e66631df8c154cbb606247 to your computer and use it in GitHub Desktop.
Example Angular v5 Http lib override to include auth headers
import { Injectable } from '@angular/core';
import {
Http,
XHRBackend,
RequestOptions,
Request,
RequestOptionsArgs,
Response,
Headers
} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { AuthService as Auth } from './auth.service';
@Injectable()
export class HttpService extends Http {
private token: string;
static useFactory(backend: XHRBackend, options: RequestOptions) {
return new HttpService(backend, options);
}
constructor (
backend: XHRBackend,
options: RequestOptions
) {
super(backend, options);
}
request(
url: string|Request,
options?: RequestOptionsArgs
): Observable<Response> {
const token = Auth.getToken();
this.token = token.value;
if (typeof url === 'string') {
if (!options) {
options = {headers: new Headers()};
}
options.headers.set('x-access-token', `${this.token}`);
} else {
url.headers.set('x-access-token', `${this.token}`);
}
return super.request(url, options)
.do((res: Response) => {
// all is well
}, (error: any) => {
// user should re-authenticate if not already on the login page
if (error.status === 403) {
Auth.logout();
}
})
.catch(this.catchAuthenticationError(this));
}
private catchAuthenticationError (self: HttpService) {
return (response: Response) => Observable.throw(response);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment