2020-06-19 08:43:22 +02:00
|
|
|
import { Injectable } 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';
|
|
|
|
|
2020-06-22 10:22:45 +02:00
|
|
|
|
2020-06-19 08:43:22 +02:00
|
|
|
@Injectable({
|
|
|
|
providedIn: 'root'
|
|
|
|
})
|
|
|
|
export class ApiService {
|
|
|
|
|
|
|
|
private host = '/api';
|
|
|
|
|
|
|
|
constructor(
|
|
|
|
private http: HttpClient,
|
|
|
|
private storage: LocalStorageService,
|
|
|
|
private modalService: ModalService
|
|
|
|
) { }
|
|
|
|
|
|
|
|
get<T>(url, f: (data?: T, err?) => void = () => {}) {
|
|
|
|
this.requestErrorHandler<T>(this.http.get(this.host + url, this.authOptions()), f);
|
|
|
|
}
|
|
|
|
|
|
|
|
post<T>(url, data = null, f: (data?: T, err?) => void = () => {}) {
|
|
|
|
this.requestErrorHandler<T>(this.http.post(this.host + url, data, this.authOptions()), f);
|
|
|
|
}
|
|
|
|
|
|
|
|
put<T>(url, data = null, f: (data?: T, err?) => void = () => {}) {
|
|
|
|
this.requestErrorHandler<T>(this.http.put(this.host + url, data, this.authOptions()), f);
|
|
|
|
}
|
|
|
|
|
|
|
|
delete<T>(url, f: (data?: T, err?) => void = () => {}) {
|
|
|
|
this.requestErrorHandler<T>(this.http.delete(this.host + url, this.authOptions()), f);
|
|
|
|
}
|
|
|
|
|
|
|
|
private requestErrorHandler<T>(observable: Observable<any>, f: (data?: T, err?) => void) {
|
|
|
|
observable.subscribe(data => {
|
|
|
|
f(data, undefined);
|
2020-06-22 10:22:45 +02:00
|
|
|
}, err => {
|
|
|
|
if (f.length === 2) {
|
|
|
|
f(undefined, err);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
const modalRef = this.modalService.openComponent(ErrorComponent);
|
|
|
|
modalRef.instance.message = 'Network request failed!';
|
|
|
|
}
|
2020-06-19 08:43:22 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
private authOptions() {
|
|
|
|
const auth = this.storage.get('basicAuth');
|
|
|
|
if (auth) {
|
|
|
|
return {headers: new HttpHeaders({Authorization: 'Basic ' + auth})};
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return {};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|