11

我正在使用启用了 Pager 的后端服务器(Java Spring)。我在 HTTP 调用上每页加载 100 条记录。

在 angular2 服务上,它使用“?page=1&size=100”作为初始调用的 API 调用,而在客户端大小的寻呼机上,它显示 10 并移动到 10 页,这很好。但我无法从服务器加载下一块数据。我检查了 ServerDataSource 并使用了 .setPaging(1,100)。

如何加载下一个数据块(2-200)以及如何实现这一点。任何提示都会有所帮助。

@Injectable()
export class AmazonService extends ServerDataSource {

constructor(protected http: Http) {
    super(http);
}

public getAmazonInformation(page, size): Observable<Amazon[]> {

    let url = 'http://localhost:8080/plg-amazon?page=1&size=100';
    this.setPaging(1, 100, true);
    if (this.pagingConf && this.pagingConf['page'] && 
       this.pagingConf['perPage']) {
          url += 
       `page=${this.pagingConf['page']}&size=${this.pagingConf['perPage']}`;
}

return this.http.get(url).map(this.extractData).catch(this.handleError);
}

谢谢!

4

5 回答 5

7

我解决了这个问题LocalDataSource

HTML

<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>

TS

source: LocalDataSource = new LocalDataSource();
pageSize = 25;

ngOnInit() {
  this.source.onChanged().subscribe((change) => {
    if (change.action === 'page') {
      this.pageChange(change.paging.page);
    }
  });
}

pageChange(pageIndex) {
  const loadedRecordCount = this.source.count();
  const lastRequestedRecordIndex = pageIndex * this.pageSize;

  if (loadedRecordCount <= lastRequestedRecordIndex) {    
    let myFilter; //This is your filter.
    myFilter.startIndex = loadedRecordCount + 1;
    myFilter.recordCount = this.pageSize + 100; //extra 100 records improves UX.

    this.myService.getData(myFilter) //.toPromise()
      .then(data => {
        if (this.source.count() > 0){
          data.forEach(d => this.source.add(d));
          this.source.getAll()
          .then(d => this.source.load(d))
      }
        else
          this.source.load(data);
      })
  }
}
于 2019-04-10T07:27:11.807 回答
2

尝试像这样将设置设置为智能表

<ng2-smart-table #grid [settings]="settings" ... >

在您的组件中,定义设置,如下所示:

  public settings: TableSettings = new TableSettings();

  ngOnInit(): void {
      ...
    this.settings.pager.display = true;
    this.settings.pager.perPage = 100;
    ...
  }

于 2017-06-21T13:45:07.863 回答
1

此外,如果您需要自定义对后端的请求,还有ServerDataSource用于数据检索/分页/排序的配置参数。

在此处输入图像描述

于 2018-08-16T07:48:53.840 回答
0

当您在{endPointBase}/ng2-smart-table上拥有某个实体的端点时,您正在处理key_like请求参数(即:@Requestparam Map to spring data Example),您可以在客户端使用:

export class SpringDataSource extends ServerDataSource {
    constructor(http: HttpClient, endPointBase: string) {
        const serverSourceConf = new ServerSourceConf();
        serverSourceConf.dataKey = 'content';
        serverSourceConf.endPoint = endPointBase + `/ng2-smart-table`;
        serverSourceConf.pagerLimitKey = 'size';
        serverSourceConf.pagerPageKey = 'page';
        serverSourceConf.sortFieldKey = 'sort';
        serverSourceConf.totalKey = 'totalElements';

        super(http, serverSourceConf);
    }

    protected addPagerRequestParams(httpParams: HttpParams): HttpParams {
        const paging = this.getPaging();
        return httpParams
            .set(this.conf.pagerPageKey, (paging.page - 1).toString())
            .set(this.conf.pagerLimitKey, paging.perPage.toString());
    }

    protected addSortRequestParams(httpParams: HttpParams): HttpParams {
        const sort: {field: string, direction: string}[] = this.getSort();

        sort.forEach((column) => {
            httpParams = httpParams.append(this.conf.sortFieldKey, `${column.field},${column.direction}`);
        });
        return httpParams;
    }
}
于 2020-04-09T12:00:57.193 回答
0

这是我解决所有这些问题的方法。

1:确保后端(API)启用了 cors 以向客户端显示“X-Pagination”标头,如下所示:

app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().WithExposedHeaders(new string[] { "X-Pagination"}));

2:HTML:

<ng2-smart-table [settings]="settings" [source]="source"></ng2-smart-table>

3:服务:

getClients(pageNumber: number, pageSize: number): Observable<any> {
            const headers = new HttpHeaders({'Content-Type': 'application/json','Accept': 'application/json' });
            let params = new HttpParams();
            params = params.append('PageNumber',pageNumber.toString());
            params = params.append('PageSize',pageSize.toString());
            return this.http.get<ClientDto[]>(API_URL, {headers: headers, observe: "response" as "body",  responseType: "json", params} );
          }

4:TS:

export class ListClientComponent implements OnInit {

  source: LocalDataSource;
  pageSize = 30;
  currentPage = 1;
  showPerPage = 10;
  totalCount;
  constructor(private service: ClientService,private router: Router) {
    this.initData();
  }

  public settings = {
    mode: 'external', 
    pager:{
      display: true,
      perPage: this.showPerPage,
    },
    actions: {
      add:false,
      edit:true,
      delete:false
    },
        columns: {
      clientId: {
        title: 'CI',
      },
      name: {
        title: 'Name'
      },
      instagramName: {
        title: 'Instagram'
      },
      type: {
        title: 'Type'
      },
      phone: {
        title: 'Phone'
      },
      gender: {
        title: 'Gender'
      },
      age: {
        title: 'Age'
      },
      city: {
        title: 'City'
      },
      email: {
        title: 'Email'
      }
    },
  };

  ngOnInit() {
    this.initOnChagedData();
  }

  onEdit(event){
    console.log(event.data.clientId);
    this.router.navigate(['/clients/update-client/'+ event.data.clientId]) ;  
  }

  initData(){
    this.source = new LocalDataSource();
    this.service.getClients(this.currentPage, this.pageSize).subscribe( (result: HttpResponse<any>) => {
      if(!result){
        return;
      }
      this.source.load(result.body);
      this.totalCount = JSON.parse(result.headers.get("X-Pagination"));
      this.totalCount = this.totalCount["totalCount"];
      console.log(this.source.count());
    }
    )
  }

  initOnChagedData(){
    this.source.onChanged().subscribe((change) => {
      if (change.action === 'page') {
        this.pageChange(change.paging.page);
      }
    });
  }

  pageChange(pageIndex) {
    var getNew = pageIndex * this.showPerPage;
    if( getNew >= this.source.count() && getNew < this.totalCount){
      this.currentPage = this.currentPage + 1;
      this.service.getClients(this.currentPage, this.pageSize).subscribe( result => {
        if(!result){
          return;
        }
        result.body.forEach(element => {
          this.source.add(element);
        });
      })
    }
  }
}

您应该注意到 pageSize = 我们从后端提取的总数据并显示每页 = 我们在表中显示的总数据。

该算法被设计为仅在必要时从 API 中提取,即当客户端到达数据在内存中结束的页面时,它会要求再多 30 条数据有另外 3 个页面,并且也不会忘记另外 3 个页面之前已经提取的。

于 2021-06-03T01:18:17.237 回答