import { Injectable } from '@angular/core'; import { Response, ResponseContentType, Http, Headers} from '@angular/http'; import { UserService } from './../service/common/user.service'; import { environment } from '../environments/environment'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; @Injectable() export class HttpClient { constructor(private http: Http, private userService: UserService, private router: Router) { } private createAuthorizationHeader(headers: Headers) { if (this.userService.authentication && this.userService.authentication.accessToken) { headers.append('Authorization', `Bearer ${this.userService.authentication.accessToken}`); if (environment.envName === 'test') { headers.append('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept'); } } headers.append('content-type', 'application/json'); } private createSimpleHeader(headers: Headers) { if (this.userService.authentication && this.userService.authentication.accessToken) { headers.append('Authorization', `Bearer ${this.userService.authentication.accessToken}`); } headers.append('content-type', 'application/json'); } public getBlob(url) { const headers = new Headers(); this.createSimpleHeader(headers); this.enforceAuthorization(); return this.http.get(url, { headers: headers, responseType: ResponseContentType.Blob }); } public get(url, params) { const headers = new Headers(); this.createAuthorizationHeader(headers); this.enforceAuthorization(); return this.http.get(this.enrichUrl(url, params), { headers: headers }); } public getWithOptions(url, options, params) { const headers = new Headers(); this.createAuthorizationHeader(headers); options.headers = headers; this.enforceAuthorization(); return this.http.get(this.enrichUrl(url, params), options); } public post(url, data) { const headers = new Headers(); this.createAuthorizationHeader(headers); this.enforceAuthorization(); return this.http.post(this.enrichUrl(url, ''), data, { headers: headers }); } public put(url, data, params) { const headers = new Headers(); this.createAuthorizationHeader(headers); this.enforceAuthorization(); return this.http.put(this.enrichUrl(url, params), data, { headers: headers }); } public enforceAuthorization() { if (!this.userService.isAuthenticated) { this.router.navigate(['/']); } } private enrichUrl(url, params) { let actualUrl = url; if (actualUrl.slice(-1) === '/') { actualUrl = actualUrl.slice(0, actualUrl.length - 1); } if (environment.envName !== 'test') { actualUrl = actualUrl + '/v1'; } if (params) { actualUrl = actualUrl + params; } // actualUrl = actualUrl.replace('//', '/'); return actualUrl; } }