javascriptangulartypescriptng2-smart-table

Pass value to extends plugin ng2 smart table


I've checked the document and source code for pagination implementation (advanced-example-server.component.ts).

And found that the ServerDataSource it used had only implemented pagination via HTTP GET (_sort, _limit, _page, etc parameters expose in URL)..... as my current project worked on required to use POST to send front-end parameters to back-end Restful APIs,

using extends to HTTP post call implement, I don't know how to add the extra parameters in pagination request. I Need To pass the request_server to extendsplugin.ts

import { Observable } from 'rxjs/internal/Observable';
import { ServerDataSource } from 'ng2-smart-table';

    export class PostServerDataSource extends ServerDataSource {

        protected requestElements(): Observable<any> {
            let httpParams = this.createRequesParams();
            return this.http.post(this.conf.endPoint, request_server, { observe: 'response' });
        }

    }

anotherComponent.ts

swiftListTable() {

        const request_server = { "userType": this.currentUser.role, "authName": this.currentUser.username }
        this.source = new PostServerDataSource(this.http,{endPoint: this.service.apiURL + 'swift/pagination', dataKey: 'content', pagerLimitKey:"_limit",
        pagerPageKey:"_page",
        sortDirKey: "pageable",
        sortFieldKey: "pageable",
        totalKey:'totalElements'});
      }

Solution

  • There are two ways you can handle it, one way is attaching the params in query string and append to url like,

    this.service.apiURL + 'swift/pagination?param1=p&param2=q'
    

    Other way could be handling it in requestElements and swiftListTable functions like below.

    swiftListTable() {
    
            const request_server = { 
               "userType": this.currentUser.role, 
               "authName": this.currentUser.username 
            }
    
           this.source = new PostServerDataSource(http, 
              { endPoint: url, dataKey: 'content', pagerLimitKey:'_limit'}, request_server);
    

    export class PostServerDataSource extends ServerDataSource {
    
        params: any;
    
        constructor(http: HttpClient, config: any, params?: any) {
            super(http, config);
            this.params = params;
        }
    
        protected requestElements(): Observable<any> {
            let httpParams = this.createRequesParams();
            if (this.params) {
              let keys = Object.keys(this.params);
              keys.forEach((key) => {
                  httpParams = httpParams.set(key, this.params[key]);
              });
            }
            return this.http.post(this.conf.endPoint, httpParams, { observe: 'response' });
        }
    
    }