$http.获取同步 AngularJS

$http.get to synchronous AngularJS

本文关键字:AngularJS 同步 获取 http      更新时间:2023-09-26

你能帮我吗,请我刚开始在angularJS,

我对异步 $http.get 有问题,我解释说:我得到了我在 ngTable 中显示的数据,但在我的 html 中我得到了一个空表,直到我单击过滤或排序然后我看到我的数据。

我想这是因为我的http.get中有一个承诺。 在这里,我的代码可以了解更多(对不起我的英语)

'use strict';
(function() {
    angular
        .module('timeShareApp')
        .controller('homeController', homeController);

    function homeController($http, $scope, $filter, NgTableParams) {
    $scope.users =[];
$http.get('/api/users/').success(function(response) {
            $scope.users = response;
        });
       $scope.usersTable = new NgTableParams({
                page: 1,
                count: 10
            }, {
                total: $scope.users.length, 
                getData: function ($defer, params) {
                      $scope.data = params.sorting() ? $filter('orderBy')($scope.users, params.orderBy()) : $scope.users;
                       $scope.data = params.filter() ? $filter('filter')($scope.data, params.filter()) : $scope.data;
                       $scope.data = $scope.data.slice((params.page() - 1) * params.count(), params.page() * params.count());
                       $defer.resolve($scope.data);
                }
            });


 }
   homeController.$inject = ["$http", "$scope", "$filter", "NgTableParams"];
})();

对于信息:代码运行良好,除了那个承诺,如果你想帮我,我想转换为同步。

提前谢谢你

在大多数情况下,没有理由将任何数据保留在ng表的范围之外。我的建议是不要修改或引用任何范围变量,因为这可能会导致一些非常难以跟踪的时间问题。

看看真正好的ng-table文档,其中大部分都有适合您的用例的工作示例。在此处查看文档

根据过滤/排序发生的位置,您需要对此进行调整,但以下内容基本上应该有效:

$scope.loadData = function() { return $http.get('/api/users/') };
$scope.usersTable = new NgTableParams(
  {
    page: 1,
    count: 10
  }, {
    total: 0, // just the inital value - will be updated later on
    getData: function ($defer, params) {
      $scope.loadData().success(function (result) {
        // assuming your result has a total and a data field...
        // update the table params with the total amount of results
        // could also be result.length...
        params.total(result.total);
        // sort and filter your data using the params object here
        var data = result.data;
        // give back the control to the table
        $defer.resolve(data);
      });
    }
  }
);

请注意,每当服务器响应时,还要设置params.total。否则,分页将不可见。

我认为在您的

承诺resolve方法中向我添加$scope.usersTable没有问题。你试过吗?