角度 - 数组从承诺更新,整数不更新

Angular - array updating from promise, integer not updating

本文关键字:更新 整数 承诺 数组 角度      更新时间:2023-09-26

目前我有一个工厂和一个控制器。 工厂使用来自终结点的项目和数据页数进行更新。 我的data数组被识别正常,但我的pageCount(int)更新实际上从未改变过。 我已经检查以确保它实际上没有返回 0。

.factory('myService', function($http) {
    return {
        data: [],
        update: update,
        pageCount: 0
    };
    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                angular.copy(res.data.itemsArray, this.data);
                angular.copy(res.data.pageCount, this.pageCount);
                // also tried this.pageCount = res.data.pageCount;
            }.bind(this));
    }
})
.controller('myCtrl', function(myService) {
    myService.update();
    $scope.data = myService.data;
    $scope.pageCount = myService.pageCount;
});
<div>{{pageCount}}</div> // This does not update at all
<div ng-repeat="item in data">{{item}}</div>  // This works fine

您将返回一个带有 update() 函数的promise,以便您可以使用 then 来处理结果(这将给出更一致的结果):

.factory('myService', function($http) {
    return {
        update: update
    };
    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                var result = {
                    data: [],
                    update: update,
                    pageCount: 0
                };
                result.data = res.data.itemsArray;
                result.pageCount = res.data.pageCount;
                return result;
            });
    }
})
.controller('myCtrl', function(myService) {
    $scope.data = [];  
    myService.update().then(function(result) {
        $scope.data = result.data;
        $scope.pageCount = result.pageCount;
    });
});

从服务分配基元时,引用丢失。尝试从服务中的 getter 获取 pageCount。尝试覆盖服务值与作用域中的值完全不同。

它不会发生在数组上,因为它是一个引用并且您使用了 copy。

factory('myService', function($http) {
    var pc = 0;
    return {
        data: [],
        update: update,
        pageCount: function() {
            return pc;
        }
    };
    function update() {
        return $http.get('path/to/endpoint')
            .then(function(res) {
                angular.copy(res.data.itemsArray, this.data);
                pc = res.data.pageCount;
            }.bind(this));
    }
})
.controller('myCtrl', 
    function(myService) {
        myService.update();
        $scope.data = myService.data;
        $scope.pageCount = myService.pageCount;
    });
    <div>{{pageCount()}}</div> // This does not update at all
    <div ng-repeat="item in data">{{item}}</div>  // This works fine