Blame view

src/services/statement.base.service.ts 1.95 KB
1392e7de   Yarik   Awesome
1
2
  import { Headers, Http, Response } from '@angular/http';
  
a04ea953   Yarik   awe
3
  import { Observable } from 'rxjs/Observable';
1392e7de   Yarik   Awesome
4
  import 'rxjs/add/operator/toPromise';
a04ea953   Yarik   awe
5
  import 'rxjs/add/operator/map';
1392e7de   Yarik   Awesome
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  
  export abstract class StatementBaseService {
      protected abstract url: string;
      protected headers: Headers = new Headers({'Content-Type': 'application/json'});
  
      constructor(protected http: Http) { }
  
      getData(from: number = 0, to: number = 100, sort: string = null): Promise<any[]> {
          let url: string = this.url;
          url += '?from=' + from + '&to=' + to;
          if (sort) {
              url += '&sort=' + sort;
          }
          return this.http.get(url)
              .toPromise()
              .then((response: Response) => this.parseModels(response.json()))
        .catch(this.handleError);
    }
  
a04ea953   Yarik   awe
25
26
27
28
29
30
    // search(term: string): Observable<any[]> {
    //   return this.http
    //     .get(`app/heroes/?name=${term}`)
    //     .map(response => response.json().data as any[]);
    // }
  
1392e7de   Yarik   Awesome
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    update(id: number, data: string): Promise<any> {
      return this.http.post(this.url + '/update?id=' + id, data, { headers: this.headers })
        .toPromise()
        .then((response: Response) => response.json())
        .catch(this.handleError);
    }
  
    create(data: string): Promise<any> {
      return this.http.post(this.url + '/create', data, { headers: this.headers })
        .toPromise()
        .then((response: Response) => this.parseModel(response.json()))
        .catch(this.handleError);
    }
  
    delete(id: number): Promise<any> {
      return this.http.delete(this.url + '/delete?id=' + id, { headers: this.headers })
        .toPromise()
        .then((response: Response) => response.json())
        .catch(this.handleError);
    }
  
026fffbd   Yarik   Awesome
52
53
    public abstract createModel(): Object;
  
1392e7de   Yarik   Awesome
54
55
56
57
58
59
60
61
    protected handleError(error: any): Promise<any> {
      console.error('An error occured', error);
      return Promise.reject(error.message || error);
    }
  
    protected abstract parseModels(json: any): any[];
    protected abstract parseModel(json: any): any;
  }