66 lines
1.6 KiB
TypeScript
66 lines
1.6 KiB
TypeScript
import {Injectable} from "@angular/core";
|
|
import {Headers, Http, RequestMethod} from "@angular/http";
|
|
import {Router} from "@angular/router";
|
|
import {LoginService} from "./login-service/login-service";
|
|
|
|
@Injectable()
|
|
export class HttpClient {
|
|
|
|
constructor(private router: Router,
|
|
private loginService: LoginService,
|
|
private http: Http) {
|
|
}
|
|
|
|
createAuthorizationHeader() {
|
|
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
|
|
if (new Date().getTime() <= Date.parse(currentUser.tokenExpireDate)) {
|
|
let headers = new Headers();
|
|
headers.append('x-access-token', currentUser.token);
|
|
return headers;
|
|
} else {
|
|
this.loginService.logout();
|
|
this.router.navigate(['/login'])
|
|
}
|
|
}
|
|
|
|
get(url, searchParams?) {
|
|
let headers = this.createAuthorizationHeader();
|
|
let options:any = {headers: headers};
|
|
if (searchParams) {
|
|
options.search = searchParams;
|
|
}
|
|
return this.http.get(url, options);
|
|
}
|
|
|
|
post(url, data) {
|
|
let headers = this.createAuthorizationHeader();
|
|
return this.http.post(url, data, {
|
|
headers: headers
|
|
});
|
|
}
|
|
|
|
patch(url, data) {
|
|
let headers = this.createAuthorizationHeader();
|
|
return this.http.patch(url, data, {
|
|
headers: headers
|
|
});
|
|
}
|
|
|
|
delete(url) {
|
|
let 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);
|
|
}
|
|
}
|
|
|
|
}
|