WIP:Added vorgang.service.ts
[examples/angular-tour-of-heroes] / src / app / vorgang.service.ts
1 import { Injectable } from '@angular/core';
2 import { HttpClient, HttpHeaders } from '@angular/common/http';
3 import { Observable, of, EMPTY } from 'rxjs';
4 import { catchError, tap } from 'rxjs/operators';
5 import { Vorgang } from './vorgang';
6
7
8 @Injectable({
9   providedIn: 'root'
10 })
11 export class VorgangService {
12
13   gpsUrl = 'http://localhost:1991/las/';  // URL to web api
14   httpOptions = {
15     headers: new HttpHeaders({
16       'Content-Type': 'text/plain',
17       'Accept': 'application/json'
18     })
19   };
20
21   constructor(private http: HttpClient) { }
22
23   /** POST: Einen neuen Vorgang erzeugen */
24   create(vorgang: Vorgang): Observable<Vorgang> {
25     return this
26       .http
27       .post<Vorgang>(
28         this.getUrlSave(vorgang.vbId),
29         vorgang.zustand,
30         this.httpOptions)
31       .pipe(
32         tap((result: Vorgang) => this.log(`Result for ${JSON.stringify(vorgang)}: ${JSON.stringify(result)}`)),
33         catchError(this.handleError<Vorgang>('create')));
34   }
35
36   getUrlSave(vbId: string): string {
37     return this.gpsUrl + vbId + '/save';
38   }
39
40   /**
41    * Handle Http operation that failed.
42    * Let the app continue.
43    * @param operation - name of the operation that failed
44    * @param result - optional value to return as the observable result
45    */
46   private handleError<T>(operation = 'operation', result?: T) {
47     return (error: any): Observable<T> => {
48
49       // TODO: send the error to remote logging infrastructure
50       console.error(error); // log to console instead
51
52       // TODO: better job of transforming error for user consumption
53       this.log(`${operation} failed: ${error.message}`);
54
55       // Let the app keep running by returning an empty result.
56       if (result === undefined) {
57         return EMPTY as Observable<T>;
58       } else {
59         return of(result as T);
60       }
61     };
62   }
63
64   private log(message: string) {
65     console.log(message);
66   }
67 }