【问题标题】:How can I do server-side pagination with ng-table?如何使用 ng-table 进行服务器端分页?
【发布时间】:2016-06-22 12:58:01
【问题描述】:

我的代码是

$scope.loadQuestions = function() {
  $scope.questionCount = 0;
  $scope.questionTable = new NgTableParams({
    count: []
  }, {
    total: 19387,
    getData: function($defer, params) {
      $scope.filter.sort = params.orderBy();
      $scope.filter.page = params.page();
      return $http.get("/api/questions", {
        params: $scope.filter
      }).then(function(response) {
        $scope.questionCount = response.data.count;
        return response.data.questions;
      });
    }
  });
};

如果我这样做,那很好。但那是因为我硬编码了total,这显然没有意义。如果我这样做了

  return $http.get("/api/questions", {
    params: $scope.filter
  }).then(function(response) {
    params.total(response.data.count);
    $scope.questionCount = response.data.count;
    return response.data.questions;
  });

然后它ng-table 出于某种原因两次触发http 请求。那么正确的做法是什么?

【问题讨论】:

  • 虽然可以理解你想要什么,但你的问题让我很困惑。
  • 哪一部分 - 我很乐意澄清?
  • 他们在real world example 中没有这样做吗?

标签: javascript angularjs pagination ngtable


【解决方案1】:

假设您使用的是旧版本的 ng-table 脚本之一,第一步是从您的 api 服务获取数据,然后初始化您想要的 ng-table 参数。

使用$http 服务,如果请求成功,您将仅一次获得数据,并在该服务中初始化您的 ngTableParams。因此,您将避免多次回调的问题。

还请注意 getData 中的更改部分如何通过分页解决排序和过滤问题。

这是我在项目中使用的解决方案,希望对您有所帮助。

$http.get('/api/questions').success(function (data) {
                $scope.questionTable = new ngTableParams({
                    page: 1,
                    count: 10
                },
                {
                  total: data.length,
                  getData: function ($defer, params) {
                    var filteredData = params.filter() ? $filter('filter')(data, params.filter()) : data;
                    var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : data;
                    params.total(orderedData.length);
                    $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                }
        });
});

【讨论】:

  • 当然它不必是服务器端分页,但在这种情况下,我给出了正常工作的一般解决方案。这不是拒绝我的答案的理由......
  • 该问题专门针对服务器端分页
【解决方案2】:

我不确定下面是否能解决您的问题,但我确实使用下面的代码并且它不会导致双重调用问题

                getData: function ($defer, params) {
                    if (timeout) $timeout.cancel(timeout);
                    timeout = $timeout(function () {
                        callback().then(function (data) {
                            params.total(data.TotalCount);
                            $defer.resolve(data.PageData);
                        });
                    }, 700);
                }

注意:上面粘贴的代码是指令的一部分,$timeout 部分是为了避免多次调用(节流),callback() 执行实际的 $http 调用。

从这里为您采取的重要部分可能是:$defer.resolve(data.PageData) 正在为我做伎俩 也没有像你的情况那样的return 声明。

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 2021-06-05
    • 2021-08-18
    • 1970-01-01
    • 2013-07-21
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多