definma-ui/src/app/services/api.service.ts

74 lines
2.3 KiB
TypeScript
Raw Normal View History

2020-07-13 10:52:10 +02:00
import { Injectable, isDevMode } from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {LocalStorageService} from 'angular-2-local-storage';
import {Observable} from 'rxjs';
import {ErrorComponent} from '../error/error.component';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
@Injectable({
providedIn: 'root'
})
export class ApiService {
2020-07-13 10:52:10 +02:00
private host = isDevMode() ? '/api' : 'https://definma-api.apps.de1.bosch-iot-cloud.com';
constructor(
private http: HttpClient,
private storage: LocalStorageService,
2020-07-22 10:45:34 +02:00
private modalService: ModalService,
private window: Window
) { }
2020-07-13 10:52:10 +02:00
get hostName() {
return this.host;
}
2020-07-13 10:52:10 +02:00
get<T>(url, f: (data?: T, err?, headers?) => void = () => {}) {
this.requestErrorHandler<T>(this.http.get(this.host + url, this.options()), f);
}
2020-07-13 10:52:10 +02:00
post<T>(url, data = null, f: (data?: T, err?, headers?) => void = () => {}) {
this.requestErrorHandler<T>(this.http.post(this.host + url, data, this.options()), f);
}
2020-07-13 10:52:10 +02:00
put<T>(url, data = null, f: (data?: T, err?, headers?) => void = () => {}) {
this.requestErrorHandler<T>(this.http.put(this.host + url, data, this.options()), f);
}
2020-07-13 10:52:10 +02:00
delete<T>(url, f: (data?: T, err?, headers?) => void = () => {}) {
this.requestErrorHandler<T>(this.http.delete(this.host + url, this.options()), f);
}
private requestErrorHandler<T>(observable: Observable<any>, f: (data?: T, err?, headers?) => void) {
observable.subscribe(data => {
2020-07-13 10:52:10 +02:00
f(data.body, undefined, data.headers.keys().reduce((s, e) => {s[e.toLowerCase()] = data.headers.get(e); return s; }, {}));
}, err => {
if (f.length === 2) {
f(undefined, err);
}
else {
const modalRef = this.modalService.openComponent(ErrorComponent);
modalRef.instance.message = 'Network request failed!';
2020-07-22 10:45:34 +02:00
modalRef.result.then(() => {
this.window.location.reload();
});
}
});
}
2020-07-13 10:52:10 +02:00
private options(): {headers: HttpHeaders, observe: 'body'} {
return {headers: this.authOptions(), observe: 'response' as 'body'};
}
private authOptions(): HttpHeaders {
const auth = this.storage.get('basicAuth');
if (auth) {
2020-07-13 10:52:10 +02:00
return new HttpHeaders({Authorization: 'Basic ' + auth});
}
else {
2020-07-13 10:52:10 +02:00
return new HttpHeaders();
}
}
}