How to use datasoure in ng2-ya-table?

278 views Asked by At

In the documentation of ng2-ya-table the datasource function is written in this way :

public datasource: any = (request: any): Observable<any> => {
return this.service.getUsers(request);
}

And used like this :

<ng2-ya-table [options]="options" [columns]="columns" [datasource]="datasource" [paging]="paging">
</ng2-ya-table>

I don't want to use this function in this way because I have static

data = [
    {
        name: 'Patricia',
        email: '[email protected]',
        username: 'Yes',
    },
    {
        name: 'Chelsey Dietrich',
        email: '[email protected]',
        username: 'No',
    }
]

Is that possible or I am obliged to render observable type? I tried a lot using static data but in vain

public datasource: any = {
    return this.data ;
}

why this function is not working?

2

There are 2 answers

1
vitocmpl On BEST ANSWER

Try with:

public datasource: any = (request: any): Observable<any> => {
  return Observable.of({
    recordsTotal: this.data.length,
    recordsFiltered: this.data.length,
    data: this.data
  });
}

Anyway, you need to perform pagination, sorting and filtering client side (the data source is an Observable in order to perform this operation server side). For example (pagination only):

public datasource: any = (request: any): Observable<any> => {
  let page = (request.start / request.length) + 1;
  return Observable.of({
    recordsTotal: this.data.length,
    recordsFiltered: this.data.length,
    data: this.data.slice(request.length * (page - 1), request.length * page)
  });
}
0
TSG On

I tried:

public datasource: any = (request: any): Observable<any> => {
  return Observable.of(this.data);
}

but it causes a cascade of errors starting with:

Ng2YaTableComponent.html:53 ERROR TypeError: Cannot read property 'length' of undefined

If someone can improve this answer perhaps we can find an solution