import { Headers, Http, Response } from '@angular/http'; import { IGetRowsParams } from 'ag-grid/main'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/map'; export abstract class StatementBaseService { protected abstract url: string; protected headers: Headers = new Headers({'Content-Type': 'application/json'}); constructor(protected http: Http) { } // getData2(from: number = 0, to: number = 100, sort: string = null): Promise { // 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); // } getData(params: IGetRowsParams): Observable { let sort: string = null; if (params.sortModel.length) { sort = this.parseSort(params.sortModel[0]); } let url: string = this.url; url += '?from=' + params.startRow + '&to=' + params.endRow; if (sort) { url += '&sort=' + sort; } let filter: string = this.parseFilter(params.filterModel); if (filter) { url += '&filter=' + filter; } return this.http.get(url) .map((response: Response) => this.parseModels(response.json())); } update(id: number, data: string): Promise { 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 { 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 { return this.http.delete(this.url + '/delete?id=' + id, { headers: this.headers }) .toPromise() .then((response: Response) => response.json()) .catch(this.handleError); } public abstract createModel(): Object; protected handleError(error: any): Promise { console.error('An error occured', error); return Promise.reject(error.message || error); } protected parseSort(sort: any): string { if (sort.colId && sort.sort) { let result = sort.colId; if (sort.sort === 'desc') { result = '-' + result; } return result; } return null; } protected parseFilter(filter: Object): string { let result: string = ''; for (let property in filter) { let value: string = filter[property].filter; let operator: string = filter[property].type; let symbol: string; switch (operator) { case 'contains': symbol = '*'; break; case 'equals': symbol = '='; break; case 'notEquals': symbol = '!'; break; case 'startsWith': symbol = '^'; break; case 'endsWith': symbol = '$'; break; default: } if (symbol.length) { result += symbol + property + '_' + value + ';'; } } if (result.length) { return result; } else { return null; } } protected abstract parseModels(json: any): any[]; protected abstract parseModel(json: any): any; }