code improvements

This commit is contained in:
VLE2FE
2020-09-03 15:51:53 +02:00
parent 1440e9a6fc
commit c38d0be457
73 changed files with 276 additions and 1686 deletions

View File

@ -5,7 +5,6 @@ import {Observable} from 'rxjs';
import {ErrorComponent} from '../error/error.component';
import {ModalService} from '@inst-iot/bosch-angular-ui-components';
// TODO: find solution when client wants to visit subpage but is not logged in to redirect to login without showing request failed errors
@Injectable({
providedIn: 'root'
@ -25,6 +24,7 @@ export class ApiService {
return this.host;
}
// main HTTP methods
get<T>(url, f: (data?: T, err?, headers?) => void = () => {}) {
this.requestErrorHandler<T>(this.http.get(this.url(url), this.options()), f);
}
@ -41,20 +41,25 @@ export class ApiService {
this.requestErrorHandler<T>(this.http.delete(this.url(url), this.options()), f);
}
// execute request and handle errors
private requestErrorHandler<T>(observable: Observable<any>, f: (data?: T, err?, headers?) => void) {
observable.subscribe(data => {
f(data.body, undefined, data.headers.keys().reduce((s, e) => {s[e.toLowerCase()] = data.headers.get(e); return s; }, {}));
}, err => {
if (f.length > 1) {
observable.subscribe(data => { // successful request
f(
data.body,
undefined,
data.headers.keys().reduce((s, e) => {s[e.toLowerCase()] = data.headers.get(e); return s; }, {})
);
}, err => { // error
if (f.length > 1) { // pass on error
f(undefined, err, undefined);
}
else {
else { // handle directly
this.requestError(err);
}
});
}
requestError(err) {
requestError(err) { // network error dialog
const modalRef = this.modalService.openComponent(ErrorComponent);
modalRef.instance.message = 'Network request failed!';
const details = [err.error.status];
@ -67,7 +72,7 @@ export class ApiService {
});
}
private url(url) {
private url(url) { // detect if host was given, otherwise use default host
if (/http[s]?:\/\//.test(url)) {
return url;
}
@ -76,10 +81,12 @@ export class ApiService {
}
}
// generate request options
private options(): {headers: HttpHeaders, observe: 'body'} {
return {headers: this.authOptions(), observe: 'response' as 'body'};
}
// generate Basic Auth
private authOptions(): HttpHeaders {
const auth = this.storage.get('basicAuth');
if (auth) {