|
import { Injectable } from '@angular/core'; |
|
import { Http, Headers, RequestOptions, RequestOptionsArgs } from '@angular/http'; |
|
import { Observable } from 'rxjs/Observable'; |
|
import 'rxjs/add/operator/catch'; |
|
import 'rxjs/add/operator/map'; |
|
import 'rxjs/Rx'; |
|
|
|
import { LoaderService } from './loader.service'; |
|
import { environment } from '@env/environment'; |
|
|
|
@Injectable() |
|
export class GlobalInterceptorService { |
|
|
|
constructor(private http: Http, private loader: LoaderService) { } |
|
|
|
showLoader() { |
|
this.loader.show(); |
|
} |
|
|
|
hideLoader() { |
|
this.loader.hide(); |
|
} |
|
|
|
getFullUrl(url: string): string { |
|
var apiUrl = environment.apiUrl; |
|
if (!apiUrl.endsWith('/')) { |
|
apiUrl += '/'; |
|
} |
|
|
|
if (url === 'token') { |
|
return apiUrl + url; |
|
} |
|
|
|
return apiUrl + 'api/' + url; |
|
} |
|
|
|
private getRequestOptions(includeUserToken: boolean = false) { |
|
var requestOptions: RequestOptions = new RequestOptions(); |
|
|
|
var authData = this.getAuthenticationData(); |
|
if (includeUserToken && authData.isAuthenticated) { |
|
requestOptions.headers = new Headers(); |
|
requestOptions.headers.append('Authorization', `Bearer ${authData.userToken}`); |
|
} |
|
return requestOptions; |
|
} |
|
|
|
get(url: string, includeToken: boolean = false) { |
|
this.showLoader(); |
|
return this.http.get(this.getFullUrl(url), this.getRequestOptions(includeToken)).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
postWithOptions(url: string, body: string, options: RequestOptionsArgs) { |
|
this.showLoader(); |
|
return this.http.post(this.getFullUrl(url), body, options).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
post(url: string, body: any, includeToken: boolean = false) { |
|
this.showLoader(); |
|
return this.http.post(this.getFullUrl(url), body, this.getRequestOptions(includeToken)).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
put(url: string, body: any, includeToken: boolean = false) { |
|
this.showLoader(); |
|
return this.http.put(this.getFullUrl(url), body, this.getRequestOptions(includeToken)).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
delete(url: string, includeToken: boolean = false) { |
|
this.showLoader(); |
|
return this.http.delete(this.getFullUrl(url), this.getRequestOptions(includeToken)).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
// Patch should not be called directly but is left here for brevity |
|
patch(url: string, body: any) { |
|
this.showLoader(); |
|
return this.http.patch(this.getFullUrl(url), body).finally(() => { |
|
this.hideLoader(); |
|
}); |
|
} |
|
|
|
private getAuthenticationData(): any { |
|
var authString = localStorage.getItem('authData'); |
|
if (authString) { |
|
return JSON.parse(authString); |
|
} |
|
else { |
|
return { |
|
isAuthenticated: false |
|
} |
|
} |
|
} |
|
} |