From 1392e7de24e257d1dd8b34c13ef6b64f35658329 Mon Sep 17 00:00:00 2001 From: yarik Date: Fri, 10 Feb 2017 19:22:17 +0200 Subject: [PATCH] Awesome --- src/app/data/bus-stop/bus-stop.component.ts | 243 +++++++++++++++++++++------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ src/app/data/service-object/service-object.component.ts | 202 ++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- src/models/bus-stop.ts | 2 +- src/models/service-object.ts | 2 +- src/models/statement.base.ts | 217 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/services/bus-stop.service.ts | 54 +++++++++++++----------------------------------------- src/services/statement.base.service.ts | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 322 insertions(+), 449 deletions(-) create mode 100644 src/models/statement.base.ts create mode 100644 src/services/statement.base.service.ts diff --git a/src/app/data/bus-stop/bus-stop.component.ts b/src/app/data/bus-stop/bus-stop.component.ts index 17d7837..cc93ab1 100644 --- a/src/app/data/bus-stop/bus-stop.component.ts +++ b/src/app/data/bus-stop/bus-stop.component.ts @@ -2,6 +2,8 @@ import { Component, ViewEncapsulation, AfterViewInit } from '@angular/core'; import { TdLoadingService } from '@covalent/core'; import { GridOptions, IGetRowsParams, IRowModel } from 'ag-grid/main'; +import { StatementBase } from '../../../models/statement.base'; + import { BusStopService } from '../../../services/bus-stop.service'; import { BusStop } from '../../../models/bus-stop'; import { EditorComponent } from '../../../helpers/editor.component'; @@ -17,8 +19,6 @@ import { SurfaceTypeSelectList } from '../../../models/surface-type-select-list' import { routerTransition } from '../../../animations/router.animation'; -// only import this if you are using the ag-Grid-Enterprise - @Component({ // tslint:disable-next-line:component-selector selector: 'bus-grid', @@ -26,121 +26,41 @@ import { routerTransition } from '../../../animations/router.animation'; styleUrls: ['bus-stop.scss'], encapsulation: ViewEncapsulation.None, }) -export class BusStopComponent implements AfterViewInit { +export class BusStopComponent extends StatementBase { - private columnDefs: any[]; - private gridOptions: GridOptions; - public showGrid: boolean; - public rowCount: string; public regions: RegionSelectList[]; public states: StateCommonSelectList[]; public surfaceTypes: SurfaceTypeSelectList[]; public settlements: SettlementSelectList[]; public roads: RoadSelectList[]; public boolean: BooleanSelectList[]; - public isLoading: boolean = false; - public isBootstrapping: boolean = true; - public isSelected: boolean = false; - public isNew: boolean = false; constructor( protected service: BusStopService, - private dataService: BusStopCreateService, - private booleanService: BooleanSelectListService, - private loadingService: TdLoadingService, + protected dataService: BusStopCreateService, + protected booleanService: BooleanSelectListService, + protected loadingService: TdLoadingService, ) { - this.gridOptions = {}; - this.gridOptions.enableSorting = true; - this.gridOptions.suppressMultiSort = true; - this.gridOptions.enableServerSideSorting = true; - this.showGrid = true; - this.gridOptions.rowModelType = 'virtual'; - this.booleanService.getModels().then((models) => this.boolean = models); - this.dataService.getModels().then((models) => { - this.regions = models.regionSelectListDsM as RegionSelectList[]; - this.states = models.stateCommonSelectListDsM as StateCommonSelectList[]; - this.surfaceTypes = models.surfaceTypeSelectListDsM as SurfaceTypeSelectList[]; - this.settlements = models.settlementSelectListDsM as SettlementSelectList[]; - this.roads = models.roadSelectListDsM as RoadSelectList[]; + super(); + this.initGrid(); + this.booleanService.getModels().then((models: BooleanSelectList[]) => this.boolean = models); + this.dataService.getModels().then((models: any) => { + this.regions = models.regionSelectListDsM as RegionSelectList[]; + this.states = models.stateCommonSelectListDsM as StateCommonSelectList[]; + this.surfaceTypes = models.surfaceTypeSelectListDsM as SurfaceTypeSelectList[]; + this.settlements = models.settlementSelectListDsM as SettlementSelectList[]; + this.roads = models.roadSelectListDsM as RoadSelectList[]; }).then(() => { - this.createColumnDefs(); - this.isBootstrapping = false; + this.bootstrapGrid(); }); } - ngAfterViewInit() { - this.gridOptions.api.setDatasource(this.setRowData()); + protected createModel(): Object { + return new BusStop(); } - setRowData(): any { - // tslint:disable-next-line:typedef - let dataSource = { - rowCount: null, // behave as infinite scroll - getRows: (params: IGetRowsParams) => { - let sort = null; - if (params.sortModel.length) { - sort = this.parseSort(params.sortModel[0]); - } - this.service.getData(params.startRow, params.endRow, sort).then((data) => { - if (!data.length) { - data = [new BusStop()]; - } - let lastRow = -1; - if (data.length <= params.endRow) { - lastRow = data.length; - } - params.successCallback(data, lastRow); - }); - }, - }; - return dataSource; - } - enableLoader(): void { - if (!this.isLoading) { - this.isLoading = true; - this.loadingService.register('loading'); - } - } - disableLoader(): void { - if (this.isLoading) { - this.isLoading = false; - this.loadingService.resolve('loading'); - } - } - onDeleteConfirm(event): void { - if (window.confirm('Вы уверены что хотите удалить??')) { - event.confirm.resolve(); - } else { - event.confirm.reject(); - } - } - public addNewRow(): void { - if (this.getFirstRowID()) { - this.gridOptions.api.insertItemsAtIndex(0, [new BusStop()]); - this.isNew = true; - } - } - private parseSort(sort: any): string { - if (sort.colId && sort.sort) { - let result = sort.colId; - if (sort.sort === 'desc') { - result = '-' + result; - } - return result; - } - return null; - } - private getFirstRowID(): number { - let model = this.gridOptions.api.getModel().getRow(0); - let id: number = model.data.busStopId; - if (id) { - return id; - } else { - return null; - } - } - private createColumnDefs() { - this.columnDefs = [ + protected createColumnDefs(): any[] { + return [ { headerName: '#', width: 30, @@ -151,7 +71,7 @@ export class BusStopComponent implements AfterViewInit { }, { headerName: 'ID', - field: 'busStopId', + field: 'id', }, { headerName: 'Назва дороги', @@ -272,125 +192,4 @@ export class BusStopComponent implements AfterViewInit { }, ]; } - - private onCellClicked($event) { - console.log('onCellClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellValueChanged($event) { - if ($event.oldValue !== $event.newValue) { - let data = JSON.stringify($event.data); - let id = $event.data.busStopId; - let result = null; - if (id) { - this.enableLoader(); - result = this.service.update(id, data).then(() => this.disableLoader()); - } else { - // Protection of posting new row being already sent. - if (this.isLoading) { - return ; - } - this.enableLoader(); - result = this.service.create(data).then((busStop) => { - this.gridOptions.api.setDatasource(this.setRowData()); - this.gridOptions.api.refreshVirtualPageCache(); - this.disableLoader(); - this.isNew = false; - }); - } - } - } - - private deleteRows() { - let rows = this.gridOptions.api.getSelectedNodes(); - if (!rows.length) { - this.isSelected = false; - return ; - } - rows.forEach((element, index, array) => { - let id = element.data.busStopId; - if (id) { - this.enableLoader(); - this.service.delete(id).then(() => { - if (index === (array.length - 1)) { - this.disableLoader(); - this.gridOptions.api.setDatasource(this.setRowData()); - this.gridOptions.api.refreshVirtualPageCache(); - this.gridOptions.api.deselectAll(); - this.isNew = false; - } - }); - } - }); - } - - private onCellDoubleClicked($event) { - console.log('onCellDoubleClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellContextMenu($event) { - console.log('onCellContextMenu: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellFocused($event) { - console.log('onCellFocused: (' + $event.rowIndex + ',' + $event.colIndex + ')'); - } - - private onRowSelected($event) { - // taking out, as when we 'select all', it prints to much to the console!! - // console.log('onRowSelected: ' + $event.node.data.name); - } - - private onSelectionChanged() { - let selection = this.gridOptions.api.getSelectedNodes(); - if (selection.length) { - if (selection.length === 1) { - this.gridOptions.api.refreshVirtualPageCache(); - this.isNew = false; - } - this.isSelected = true; - } else { - this.isSelected = false; - } - } - - private onBeforeFilterChanged() { - console.log('beforeFilterChanged'); - } - - private onAfterFilterChanged() { - console.log('afterFilterChanged'); - } - - private onFilterModified() { - console.log('onFilterModified'); - } - - private onBeforeSortChanged(event) { - console.log('onBeforeSortChanged'); - } - - private onAfterSortChanged($event) { - console.log('onAfterSortChanged'); - } - - private onVirtualRowRemoved($event) { - // because this event gets fired LOTS of times, we don't print it to the - // console. if you want to see it, just uncomment out this line - // console.log('onVirtualRowRemoved: ' + $event.rowIndex); - } - - private onRowClicked($event) { - console.log('onRowClicked: ' + $event.node.data.name); - } - - public onQuickFilterChanged($event) { - this.gridOptions.api.setQuickFilter($event.target.value); - } - - // here we use one generic event to handle all the column type events. - // the method just prints the event name - private onColumnEvent($event) { - console.log('onColumnEvent: ' + $event); - } } diff --git a/src/app/data/service-object/service-object.component.ts b/src/app/data/service-object/service-object.component.ts index ea958e0..4910768 100644 --- a/src/app/data/service-object/service-object.component.ts +++ b/src/app/data/service-object/service-object.component.ts @@ -1,6 +1,8 @@ import {Component, ViewEncapsulation} from '@angular/core'; import {GridOptions} from 'ag-grid/main'; +import { StatementBase } from '../../../models/statement.base'; + import { ServiceObjectService } from '../../../services/service-object.service'; import { ServiceObject } from '../../../models/service-object'; import { EditorComponent } from '../../../helpers/editor.component'; @@ -16,98 +18,46 @@ import { SettlementSelectList } from '../../../models/settlement-select-list'; import { routerTransition } from '../../../animations/router.animation'; -// only import this if you are using the ag-Grid-Enterprise - @Component({ selector: 'service-object', templateUrl: 'service-object.component.html', styleUrls: ['service-object.scss'], encapsulation: ViewEncapsulation.None, }) -export class ServiceObjectComponent { +export class ServiceObjectComponent extends StatementBase { - public showGrid: boolean; - public rowData: any[]; - public rowCount: string; public regions: RegionSelectList[]; public states: StateCommonSelectList[]; public departmentAffiliation: DepartmentAffiliationList[]; public settlements: SettlementSelectList[]; public roads: RoadSelectList[]; public boolean: BooleanSelectList[]; - public isLoading: boolean = false; - public isBootstrapping: boolean = true; - public isSelected: boolean = true; - private columnDefs: any[]; - private gridOptions: GridOptions; constructor( protected service: ServiceObjectService, private dataService: ServiceObjectCreateService, private booleanService: BooleanSelectListService, ) { - this.gridOptions = {}; - this.gridOptions.enableSorting = true; - this.showGrid = true; - this.gridOptions.rowModelType = 'virtual'; - this.booleanService.getModels().then((models) => this.boolean = models); - this.dataService.getModels().then((models) => { - this.regions = models.regionSelectListDsM as RegionSelectList[]; - this.states = models.stateCommonSelectListDsM as StateCommonSelectList[]; - this.departmentAffiliation = models.departmentAffiliationListDsM as DepartmentAffiliationList[]; - this.settlements = models.settlementSelectListDsM as SettlementSelectList[]; - this.roads = models.roadSelectListDsM as RoadSelectList[]; - }).then(() => { - this.createColumnDefs(); - this.isBootstrapping = false; - }); - this.service.getData().then((data) => { - if (data.length){ - this.rowData = data; - } else { - this.rowData = [new ServiceObject]; - } + super(); + this.initGrid(); + this.booleanService.getModels().then((models: BooleanSelectList[]) => this.boolean = models); + this.dataService.getModels().then((models: any) => { + this.regions = models.regionSelectListDsM as RegionSelectList[]; + this.states = models.stateCommonSelectListDsM as StateCommonSelectList[]; + this.departmentAffiliation = models.departmentAffiliationListDsM as DepartmentAffiliationList[]; + this.settlements = models.settlementSelectListDsM as SettlementSelectList[]; + this.roads = models.roadSelectListDsM as RoadSelectList[]; }).then(() => { - this.gridOptions.api.setDatasource(this.setRowData(this.rowData)); - this.gridOptions.api.refreshVirtualPageCache(); + this.bootstrapGrid(); }); } - setRowData(allOfTheData) { - let dataSource = { - rowCount: null, // behave as infinite scroll - getRows: function (params) { - console.log('asking for ' + params.startRow + ' to ' + params.endRow); - // At this point in your code, you would call the server, using $http if in AngularJS. - // To make the demo look real, wait for 500ms before returning - // take a slice of the total rows - let rowsThisPage = allOfTheData.slice(params.startRow, params.endRow); - // if on or after the last page, work out the last row. - let lastRow = -1; - if (allOfTheData.length <= params.endRow) { - lastRow = allOfTheData.length; - } - // call the success callback - params.successCallback(rowsThisPage, lastRow); - }, - }; - return dataSource; - } - onDeleteConfirm(event): void { - if (window.confirm('Вы уверены что хотите удалить??')) { - event.confirm.resolve(); - } else { - event.confirm.reject(); + protected createModel(): Object { + return new ServiceObject(); } - } - public addNewRow() { - this.rowData.unshift(new ServiceObject()); - this.gridOptions.api.setDatasource(this.setRowData(this.rowData)); - this.gridOptions.api.refreshVirtualPageCache(); - } - private createColumnDefs() { - this.columnDefs = [ + protected createColumnDefs(): any[] { + return [ { headerName: '#', width: 30, @@ -118,7 +68,7 @@ export class ServiceObjectComponent { }, { headerName: 'ID', - field: 'serviceObjectId', + field: 'id', }, { headerName: 'Назва дороги', @@ -156,120 +106,4 @@ export class ServiceObjectComponent { }, ]; } - - private onCellClicked($event) { - console.log('onCellClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellValueChanged($event) { - if ($event.oldValue !== $event.newValue) { - let data = JSON.stringify($event.data); - let id = $event.data.busStopId; - let result = null; - if (id) { - this.isLoading = true; - result = this.service.update(id, data).then(() => this.isLoading = false); - } else { - // Protection of posting new row being already sent. - if (this.isLoading) { - return ; - } - this.isLoading = true; - result = this.service.create(data).then((busStop) => { - this.rowData[$event.node.rowIndex] = busStop; - this.gridOptions.api.setDatasource(this.setRowData(this.rowData)); - this.gridOptions.api.refreshVirtualPageCache(); - this.isLoading = false; - }); - } - } - } - - private deleteRows() { - let rows = this.gridOptions.api.getSelectedNodes(); - if (!rows.length) { - return ; - } - rows.forEach((element) => { - let id = element.data.busStopId; - if (id) { - this.isLoading = true; - this.service.delete(id).then(() => this.isLoading = false); - } - }); - // Sort in order to protect array from reindexing (remove rear elements first) - let sorted = rows.sort((a, b) => { - if (a > b) { - return -1; - } else { - return 1; - } - }); - sorted.forEach((item) => { - this.rowData.splice(item.rowIndex, 1); - }); - this.gridOptions.api.setDatasource(this.setRowData(this.rowData)); - this.gridOptions.api.refreshVirtualPageCache(); - } - - private onCellDoubleClicked($event) { - console.log('onCellDoubleClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellContextMenu($event) { - console.log('onCellContextMenu: ' + $event.rowIndex + ' ' + $event.colDef.field); - } - - private onCellFocused($event) { - console.log('onCellFocused: (' + $event.rowIndex + ',' + $event.colIndex + ')'); - } - - private onRowSelected($event) { - // taking out, as when we 'select all', it prints to much to the console!! - // console.log('onRowSelected: ' + $event.node.data.name); - } - - private onSelectionChanged() { - console.log('selectionChanged'); - } - - private onBeforeFilterChanged() { - console.log('beforeFilterChanged'); - } - - private onAfterFilterChanged() { - console.log('afterFilterChanged'); - } - - private onFilterModified() { - console.log('onFilterModified'); - } - - private onBeforeSortChanged() { - console.log('onBeforeSortChanged'); - } - - private onAfterSortChanged() { - console.log('onAfterSortChanged'); - } - - private onVirtualRowRemoved($event) { - // because this event gets fired LOTS of times, we don't print it to the - // console. if you want to see it, just uncomment out this line - // console.log('onVirtualRowRemoved: ' + $event.rowIndex); - } - - private onRowClicked($event) { - console.log('onRowClicked: ' + $event.node.data.name); - } - - public onQuickFilterChanged($event) { - this.gridOptions.api.setQuickFilter($event.target.value); - } - - // here we use one generic event to handle all the column type events. - // the method just prints the event name - private onColumnEvent($event) { - console.log('onColumnEvent: ' + $event); - } } diff --git a/src/models/bus-stop.ts b/src/models/bus-stop.ts index bda0065..33144cf 100644 --- a/src/models/bus-stop.ts +++ b/src/models/bus-stop.ts @@ -1,5 +1,5 @@ export class BusStop { - busStopID: number; + id: number; roadId: number; regionId: number; settlementId: number; diff --git a/src/models/service-object.ts b/src/models/service-object.ts index f786448..32788b9 100644 --- a/src/models/service-object.ts +++ b/src/models/service-object.ts @@ -1,5 +1,5 @@ export class ServiceObject{ - serviceObjectID: number; + id: number; roadId: number; regionId: number; serviceObjectTypeId: number; diff --git a/src/models/statement.base.ts b/src/models/statement.base.ts new file mode 100644 index 0000000..596e588 --- /dev/null +++ b/src/models/statement.base.ts @@ -0,0 +1,217 @@ +import { AfterViewInit } from '@angular/core'; +import { TdLoadingService } from '@covalent/core'; +import { GridOptions, IGetRowsParams, IRowModel, RowNode } from 'ag-grid/main'; + +export abstract class StatementBase implements AfterViewInit { + protected columnDefs: any[]; + protected gridOptions: GridOptions; + protected service: any; + protected loadingService: TdLoadingService; + public showGrid: boolean; + public rowCount: string; + public isLoading: boolean = false; + public isBootstrapping: boolean = true; + public isSelected: boolean = false; + public isNew: boolean = false; + + ngAfterViewInit(): void { + this.gridOptions.api.setDatasource(this.setRowData()); + } + + enableLoader(): void { + if (!this.isLoading) { + this.isLoading = true; + this.loadingService.register('loading'); + } + } + + disableLoader(): void { + if (this.isLoading) { + this.isLoading = false; + this.loadingService.resolve('loading'); + } + } + + public addNewRow(): void { + if (this.getFirstRowID()) { + this.gridOptions.api.insertItemsAtIndex(0, [this.createModel()]); + this.isNew = true; + } + } + + protected initGrid(): void { + this.gridOptions = {}; + this.gridOptions.enableSorting = true; + this.gridOptions.suppressMultiSort = true; + this.gridOptions.enableServerSideSorting = true; + this.showGrid = true; + this.gridOptions.rowModelType = 'virtual'; + } + + protected bootstrapGrid(): void { + this.columnDefs = this.createColumnDefs(); + this.isBootstrapping = false; + } + + protected setRowData(): {} { + let dataSource: {} = { + rowCount: null, + getRows: (params: IGetRowsParams) => { + let sort: string = null; + if (params.sortModel.length) { + sort = this.parseSort(params.sortModel[0]); + } + this.service.getData(params.startRow, params.endRow, sort).then((data: any) => { + if (!data.length) { + data = [this.createModel()]; + } + let lastRow: number = -1; + if (data.length <= params.endRow) { + lastRow = data.length; + } + params.successCallback(data, lastRow); + }); + }, + }; + return dataSource; + } + + 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 getFirstRowID(): number { + let model = this.gridOptions.api.getModel().getRow(0); + let id: number = model.data.id; + if (id) { + return id; + } else { + return null; + } + } + + protected onCellValueChanged($event: any): void { + if ($event.oldValue !== $event.newValue) { + let data: string = JSON.stringify($event.data); + let id: number = $event.data.id; + let result: any = null; + if (id) { + this.enableLoader(); + result = this.service.update(id, data).then(() => this.disableLoader()); + } else { + // Protection of posting new row being already sent. + if (this.isLoading) { + return ; + } + this.enableLoader(); + result = this.service.create(data).then((model: any) => { + this.gridOptions.api.setDatasource(this.setRowData()); + this.disableLoader(); + this.isNew = false; + }); + } + } + } + + protected deleteRows(): void { + let rows: RowNode[] = this.gridOptions.api.getSelectedNodes(); + if (!rows.length) { + this.isSelected = false; + return ; + } + rows.forEach((element: RowNode, index: number, array: RowNode[]) => { + let id: number = element.data.id; + if (id) { + this.enableLoader(); + this.service.delete(id).then(() => { + if (index === (array.length - 1)) { + this.disableLoader(); + this.gridOptions.api.setDatasource(this.setRowData()); + this.gridOptions.api.deselectAll(); + this.isNew = false; + } + }); + } + }); + } + + protected onSelectionChanged(): void { + let selection: RowNode[] = this.gridOptions.api.getSelectedNodes(); + if (selection.length) { + if (selection.length === 1) { + this.gridOptions.api.refreshVirtualPageCache(); + this.isNew = false; + } + this.isSelected = true; + } else { + this.isSelected = false; + } + } + + protected onCellClicked($event: any): void { + console.log('onCellClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); + } + + protected onCellDoubleClicked($event: any): void { + console.log('onCellDoubleClicked: ' + $event.rowIndex + ' ' + $event.colDef.field); + } + + protected onCellContextMenu($event: any): void { + console.log('onCellContextMenu: ' + $event.rowIndex + ' ' + $event.colDef.field); + } + + protected onCellFocused($event: any): void { + console.log('onCellFocused: (' + $event.rowIndex + ',' + $event.colIndex + ')'); + } + + protected onRowSelected($event: any): void { + // taking out, as when we 'select all', it prints to much to the console!! + // console.log('onRowSelected: ' + $event.node.data.name); + } + + protected onBeforeFilterChanged(): void { + console.log('beforeFilterChanged'); + } + + protected onAfterFilterChanged(): void { + console.log('afterFilterChanged'); + } + + protected onFilterModified(): void { + console.log('onFilterModified'); + } + + protected onBeforeSortChanged(event: any): void { + console.log('onBeforeSortChanged'); + } + + protected onAfterSortChanged($event: any): void { + console.log('onAfterSortChanged'); + } + + protected onVirtualRowRemoved($event: any): void { + // because this event gets fired LOTS of times, we don't print it to the + // console. if you want to see it, just uncomment out this line + // console.log('onVirtualRowRemoved: ' + $event.rowIndex); + } + + protected onRowClicked($event: any): void { + console.log('onRowClicked: ' + $event.node.data.name); + } + + // here we use one generic event to handle all the column type events. + // the method just prints the event name + protected onColumnEvent($event: any): void { + console.log('onColumnEvent: ' + $event); + } + + protected abstract createModel(): Object; + protected abstract createColumnDefs(): any[]; +} diff --git a/src/services/bus-stop.service.ts b/src/services/bus-stop.service.ts index 91a65cb..56bd3dd 100644 --- a/src/services/bus-stop.service.ts +++ b/src/services/bus-stop.service.ts @@ -1,46 +1,18 @@ -import { Injectable } from '@angular/core'; -import { Headers, Http } from '@angular/http'; - -import 'rxjs/add/operator/toPromise'; - import { BusStop } from '../models/bus-stop'; +import { Injectable } from '@angular/core'; +import { StatementBaseService } from '../services/statement.base.service'; +import { Http } from '@angular/http'; @Injectable() -export class BusStopService { - private url = 'http://localhost:5000/busstop'; - private headers = new Headers({'Content-Type': 'application/json'}); - constructor(private http: Http) { } - getData(from: number = 0, to: number = 100, sort: string = null): Promise { - let url = this.url; - url += '?from=' + from + '&to=' + to; - if (sort) { - url += '&sort=' + sort; - } - return this.http.get(url) - .toPromise() - .then(response => response.json().busStopEditDsM as BusStop[]) - .catch(this.handleError); - } - update(id: number, data: string): Promise { - return this.http.post(this.url + '/update?id=' + id, data, { headers: this.headers }) - .toPromise() - .then(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.json() as BusStop) - .catch(this.handleError); - } - delete(id: number): Promise { - return this.http.delete(this.url + '/delete?id=' + id, { headers: this.headers }) - .toPromise() - .then(response => response.json()) - .catch(this.handleError); - } - private handleError(error: any): Promise { - console.error('An error occured', error); - return Promise.reject(error.message || error); +export class BusStopService extends StatementBaseService { + protected url: string = 'http://localhost:5000/busstop'; + constructor(protected http: Http) { + super(http); } + protected parseModels(json: any): any[] { + return json.busStopEditDsM as BusStop[]; + }; + protected parseModel(json: any): any { + return json as BusStop; + }; } diff --git a/src/services/statement.base.service.ts b/src/services/statement.base.service.ts new file mode 100644 index 0000000..71e0cb6 --- /dev/null +++ b/src/services/statement.base.service.ts @@ -0,0 +1,51 @@ +import { Headers, Http, Response } from '@angular/http'; + +import 'rxjs/add/operator/toPromise'; + +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 { + 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); + } + + 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); + } + + protected handleError(error: any): Promise { + console.error('An error occured', error); + return Promise.reject(error.message || error); + } + + protected abstract parseModels(json: any): any[]; + protected abstract parseModel(json: any): any; +} -- libgit2 0.21.4