Created
January 16, 2018 12:17
-
-
Save andela-kakpobome/bf0e3ff860e66631df8c154cbb606247 to your computer and use it in GitHub Desktop.
Example Angular v5 Http lib override to include auth headers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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