opt-cc/static/src/app/services/http-client.ts

78 lines
1.9 KiB
TypeScript

import {Injectable} from '@angular/core';
import {Headers, Http, RequestMethod} from '@angular/http';
import {Router} from '@angular/router';
import {CookieService} from 'ngx-cookie-service';
@Injectable()
export class HttpClient {
constructor(private router: Router,
private http: Http,
private cookieService: CookieService) {
}
createAuthorizationHeader() {
const cookieField = this.cookieService.get('currentUser');
if (cookieField) {
const currentUser = JSON.parse(cookieField);
if (new Date().getTime() <= Date.parse(currentUser.tokenExpireDate)) {
const headers = new Headers();
headers.append('x-access-token', currentUser.token);
return headers;
} else {
// logout
localStorage.removeItem('currentUser');
this.router.navigate(['/login']);
}
}
}
get(url, searchParams?) {
const headers = this.createAuthorizationHeader();
const options: any = {headers: headers};
if (searchParams) {
options.search = searchParams;
}
return this.http.get(url, options);
}
post(url, data) {
const headers = this.createAuthorizationHeader();
return this.http.post(url, data, {
headers: headers
});
}
put(url, data) {
const headers = this.createAuthorizationHeader();
return this.http.put(url, data, {
headers: headers
});
}
patch(url, data) {
const headers = this.createAuthorizationHeader();
return this.http.patch(url, data, {
headers: headers
});
}
delete(url) {
const headers = this.createAuthorizationHeader();
return this.http.delete(url, {
headers: headers
});
}
request(requestUrl, options) {
if (options.method === RequestMethod.Post) {
return this.post(requestUrl, options.body);
}
if (options.method === RequestMethod.Patch) {
return this.patch(requestUrl, options.body);
}
}
}