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