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

78 lines
1.9 KiB
TypeScript
Raw Normal View History

2018-03-07 11:56:50 +01:00
import {Injectable} from '@angular/core';
import {Headers, Http, RequestMethod} from '@angular/http';
import {Router} from '@angular/router';
import {CookieService} from 'ngx-cookie-service';
2017-05-10 11:04:06 +02:00
@Injectable()
export class HttpClient {
constructor(private router: Router,
2017-09-23 11:53:10 +02:00
private http: Http,
private cookieService: CookieService) {
2017-05-10 11:04:06 +02:00
}
createAuthorizationHeader() {
2017-09-23 12:05:51 +02:00
const cookieField = this.cookieService.get('currentUser');
if (cookieField) {
const currentUser = JSON.parse(cookieField);
if (new Date().getTime() <= Date.parse(currentUser.tokenExpireDate)) {
2018-03-07 11:56:50 +01:00
const headers = new Headers();
headers.append('x-access-token', currentUser.token);
return headers;
} else {
2018-03-07 11:56:50 +01:00
// logout
2017-07-27 16:38:35 +02:00
localStorage.removeItem('currentUser');
2018-03-07 11:56:50 +01:00
this.router.navigate(['/login']);
}
2017-05-10 11:04:06 +02:00
}
2017-09-23 12:05:51 +02:00
2017-05-10 11:04:06 +02:00
}
get(url, searchParams?) {
2018-03-07 11:56:50 +01:00
const headers = this.createAuthorizationHeader();
const options: any = {headers: headers};
2017-05-10 11:04:06 +02:00
if (searchParams) {
options.search = searchParams;
}
return this.http.get(url, options);
}
post(url, data) {
2018-03-07 11:56:50 +01:00
const headers = this.createAuthorizationHeader();
2017-05-10 11:04:06 +02:00
return this.http.post(url, data, {
headers: headers
});
}
2017-05-13 14:57:40 +02:00
put(url, data) {
2018-03-07 11:56:50 +01:00
const headers = this.createAuthorizationHeader();
2017-05-13 14:57:40 +02:00
return this.http.put(url, data, {
headers: headers
});
}
2017-05-10 11:04:06 +02:00
patch(url, data) {
2018-03-07 11:56:50 +01:00
const headers = this.createAuthorizationHeader();
2017-05-10 11:04:06 +02:00
return this.http.patch(url, data, {
headers: headers
});
}
delete(url) {
2018-03-07 11:56:50 +01:00
const headers = this.createAuthorizationHeader();
2017-05-10 11:04:06 +02:00
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);
}
}
}