使用angular.copy()复制ngResource返回的数据时出现错误

3

我有以下代码:

getContents: function ($scope, entityType, action, subjectId, contentTypeId, contentStatusId) {
                entityService.getContents(entityType, action, subjectId, contentTypeId, contentStatusId)
                .then(function (result) {
                    $scope.grid.data = result;
                    angular.copy($scope.grid.data, $scope.grid.originalData);
                    $scope.grid.newButtonEnabled = true;
                }, function (result) {
                    alert("Error: No data returned");
                    $scope.grid.newButtonEnabled = false;
                });
            },

然后在entityService中有以下函数:

        getContents: function (entityType, action, subjectId, contentTypeId, contentStatusId) {
            var deferred = $q.defer();
            EntityResource.getEntities({ entityType: entityType, subjectId: subjectId, contentTypeId: contentTypeId, contentStatusId: contentStatusId },
               function (resp) {
                   deferred.resolve(resp);
               }
            );
            return deferred.promise;
        },

当我尝试使用angular.copy时,会出现一条消息:

TypeError: Object #<Object> has no method 'push'
    at Object.copy (http://127.0.0.1:81/Scripts/angular.js:600:21)
    at factory.getContents.entityService.getContents.then.$scope.grid.newButtonEnabled (http://127.0.0.1:81/Content/app/admin/services/grid-service.js:303:29)
    at deferred.promise.then.wrappedCallback (http://127.0.0.1:81/Scripts/angular.js:7303:59)
    at ref.then (http://127.0.0.1:81/Scripts/angular.js:7340:26)
    at Object.$get.Scope.$eval (http://127.0.0.1:81/Scripts/angular.js:8685:28)
    at Object.$get.Scope.$digest (http://127.0.0.1:81/Scripts/angular.js:8548:23)
    at Object.$get.Scope.$apply (http://127.0.0.1:81/Scripts/angular.js:8771:24)
    at done (http://127.0.0.1:81/Scripts/angular.js:10004:20)
    at completeRequest (http://127.0.0.1:81/Scripts/angular.js:10180:7)
    at XMLHttpRequest.xhr.onreadystatechange (http://127.0.0.1:81/Scripts/angular.js:10144:11) 

你知道如何复制返回的数据吗?请注意,这些数据来自ngResource。此外,这似乎不同于我在Stackoverflow上找到的其他问题,与“TypeError: Object # has no method 'push'”相关的问题。 对于这个问题,当我尝试angular.copy数据时,我得到了正确的数据,但是它会报错。

1个回答

9
请仔细查看angular.copy文档

destination(可选)- {(Object | Array) =} - 源复制到的目标。如果提供,则必须与源具有相同的类型。

你从服务调用中得到的结果很可能是一个数组;但是,你初始化了$scope.grid.originalData为对象或其他不是数组的东西,因此你会得到这种类型错误。
试着找出result的类型,并在调用angular.copy之前将$scope.grid.originalData设置为相同的类型。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接