Skip to content

Instantly share code, notes, and snippets.

@vrkansagara
Last active July 15, 2022 06:30
Show Gist options
  • Save vrkansagara/73b9ba61ce9acb0a10fc189c677bb59a to your computer and use it in GitHub Desktop.
Save vrkansagara/73b9ba61ce9acb0a10fc189c677bb59a to your computer and use it in GitHub Desktop.
Extending Angular HttpClient With Access Token Capability
import {
HttpClient,
HttpHeaders,
HttpParams,
HttpParamsOptions
} from '@angular/common/http';
import {Injectable, Injector} from '@angular/core';
import {Observable} from 'rxjs';
import {ConfigService} from '../../services/config.service';
/**
* Original code belong to bellow owners
*
* @ref https://www.bbogdanov.dev/post/extend-httpclient
* @gist https://gist.github.com/bbogdanov/e573c9d1cc8468211b35964a942aa688
* @usage
* (1) Add into app.module.ts at providers: []
* (2)) {provide: ApplicationHttpClient, useFactory: applicationHttpClientCreator, deps: [Injector,ConfigService],},
*/
export interface IRequestOptions {
headers?: HttpHeaders | any;
observe?: 'body';
params?: HttpParams | string | any;
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
body?: any;
}
export function applicationHttpClientCreator(
injector: Injector,
configService: ConfigService
) {
return new ApplicationHttpClient(
injector,
configService,
);
}
@Injectable({ providedIn: 'root' })
export class ApplicationHttpClient {
private http: HttpClient;
private httpOptions: IRequestOptions;
private api = 'https://example.com';
private subdomain = '';
// Extending the HttpClient through the Angular DI.
public constructor(
private _injector: Injector,
private configService: ConfigService
) {
this.setHttpClientOptions();
// this.http = this._injector.get(HttpClient);
this.http = this._injector.get(HttpClient);
this.api = this.configService.get('api').baseUrl;
// If you don't want to use the extended versions in some cases you can access the public property and use the original one.
// for ex. this.httpClient.http.get(...)
}
public setHttpClientOptions(): void {
// Set subdomain
if (window.location.host.split('.').length > 1){
this.subdomain = window.location.host.split('.')[0];
}
const headers = new HttpHeaders()
// .set('Content-Type', 'application/x-www-form-urlencoded')
.set('Content-Type', 'application/json')
.set('Accept', 'application/json, text/plain, */*')
.set('X-host', this.subdomain)
.set('Authorization','Bearer ' + window.localStorage.getItem('accessToken'));
// Get access token
if (window.localStorage.getItem('accessToken')){
// headers = headers.set('Authorization','Bearer ' + window.localStorage.getItem('accessToken'));
}else{
window.localStorage.removeItem('accessToken');
}
const httpParameters: any = {};
const httpParams: HttpParamsOptions = {fromObject: httpParameters} as HttpParamsOptions;
this.httpOptions = {
params: new HttpParams(httpParams),
headers: headers,
};
}
/**
* GET request
*
* @param endPoint it doesn't need / in front of the end point
* @param options options of the request like headers, body, etc.
* @returns
*/
public get<T>(endPoint: string, options?: IRequestOptions): Observable<T> {
if (options && options.params){
this.httpOptions.params = options.params;
}
return this.http.get<T>(this.api + endPoint, this.httpOptions);
}
/**
* POST request
*
* @param endPoint end point of the api
* @param params body of the request.
* @param options options of the request like headers, body, etc.
* @returns
*/
public post<T>(endPoint: string, params: Object, options?: IRequestOptions): Observable<T> {
if (options && options.params){
this.httpOptions.params = options.params;
}
return this.http.post<T>(this.api + endPoint, params, this.httpOptions);
}
/**
* PUT request
*
* @param endPoint end point of the api
* @param params body of the request.
* @param options options of the request like headers, body, etc.
* @returns
*/
public put<T>(endPoint: string, params: Object, options?: IRequestOptions): Observable<T> {
if (options && options.params){
this.httpOptions.params = options.params;
}
return this.http.put<T>(this.api + endPoint, params, this.httpOptions);
}
public patch<T>(endPoint: string, params: Object, options?: IRequestOptions): Observable<T> {
if (options && options.params){
this.httpOptions.params = options.params;
}
return this.http.patch<T>(this.api + endPoint, params, this.httpOptions);
}
/**
* DELETE request
*
* @param endPoint end point of the api
* @param options options of the request like headers, body, etc.
* @returns
*/
public delete<T>(endPoint: string, options?: IRequestOptions): Observable<T> {
if (options && options.params){
this.httpOptions.params = options.params;
}
return this.http.delete<T>(this.api + endPoint, this.httpOptions);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment