1 import { Http, RequestOptionsArgs, URLSearchParams, Response } from '@angular/http'
3 import { ServerDataSource } from 'ng2-smart-table'
5 export class RestDataSource extends ServerDataSource {
6 private updateResponse: (input: any[]) => any[]
8 constructor (http: Http, endpoint: string, updateResponse?: (input: any[]) => any[]) {
17 this.updateResponse = updateResponse
21 protected extractDataFromResponse (res: Response) {
22 const json = res.json()
26 if (this.updateResponse !== undefined) {
27 data = this.updateResponse(data)
33 protected extractTotalFromResponse (res: Response) {
34 const rawData = res.json()
35 return rawData ? parseInt(rawData.total, 10) : 0
38 protected addSortRequestOptions (requestOptions: RequestOptionsArgs) {
39 const searchParams = requestOptions.params as URLSearchParams
42 this.sortConf.forEach((fieldConf) => {
43 const sortPrefix = fieldConf.direction === 'desc' ? '-' : ''
45 searchParams.set(this.conf.sortFieldKey, sortPrefix + fieldConf.field)
52 protected addPagerRequestOptions (requestOptions: RequestOptionsArgs) {
53 const searchParams = requestOptions.params as URLSearchParams
55 if (this.pagingConf && this.pagingConf['page'] && this.pagingConf['perPage']) {
56 const perPage = this.pagingConf['perPage']
57 const page = this.pagingConf['page']
59 const start = (page - 1) * perPage
62 searchParams.set('start', start.toString())
63 searchParams.set('count', count.toString())