【问题标题】:AngualrJS client error after calling resource.$save: "TypeError: Object #<Resource> has no method 'push'"调用 resource.$save 后 AngularJS 客户端错误:“TypeError: Object #<Resource> has no method 'push'”
【发布时间】:2014-03-31 02:46:14
【问题描述】:

我正在开发一个 AngularJS 应用程序。我对 AngularJS 很陌生...

一切正常(加载数据、保存对现有记录的修改、删除)。问题在于使用从 REST 服务返回的 JSON 数据更新客户端模型。服务器端代码运行正常,数据库更改已应用。

例如: 我以这种方式将新记录插入客户端模型:

$scope.addnewpage = function ($event){
        var newItem  = new Page();
        newItem.id = '-1'; // Indicates to the REST that it's an INSERT!      
        newItem.page_name = 'New Page';
        newItem.page_title_en = 'New Page';
        newItem.page_title_hu = 'Új oldal';
        newItem.mnu_title_hu = 'Nem Page';
        newItem.mnu_title_en = 'Új oldal';
        newItem.page_text_en = '...';
        newItem.page_text_hu = '...';
        newItem.page_footer_en = '...';
        newItem.page_footer_hu = '...';
        newItem.weight = '1';

        var idx = $scope.pages.push(newItem)-1;
        $scope.pages[idx].active = true;            
    }

在服务器端,我有一个 PHP REST 服务,它可以区分 ID 字段是否包含 -1(插入新)或大于 0 的整数(更新现有)。

如果 REST 以正确的 JSON 格式向客户端返回包含 NEW id 和其他调整字段的新记录,AngularJS 将无法理解它会在浏览器控制台上发送上述错误消息。

"TypeError: Object #<Resource> has no method 'push'"

我的服务看起来像这样(我尝试更改 isArray 属性 true/false - 同样的错误):

AdminModule.factory('Page', function($resource) {
    return $resource(
        '../admin/itcrest.php/page/:id',
        {id : '@id'},
        {  
           'get':    {method:'GET', isArray:false},
           'query':  {method:'GET', isArray:true},
           'save':   {method:'POST', isArray:true},
           'delete': {method:'PUT', isArray:true} 
        }
    );
});

我保存的控制器代码 sn-p 是这样的:

AdminModule.controller('PagesListController',  
    function ($scope, $http, $timeout, Page, $location, MessageBus, $modal) {
    // ...
    $scope.savepage = function (item, $event){
        item.$save(item, function(responseData) {}, 
            function(error) { });
    }
    // ...
 }

谁能帮助我如何在不重新加载整个页面的情况下管理新记录插入,并使用来自服务器的实际数据更新客户端?我真正想做的是从 REST 服务返回真实数据,并使用新数据更新客户端模型记录——无论是在 UPDATE 和 INSERT 时。如果我返回空 JSON 以外的任何内容,它会发送错误。

由于服务器端代码运行良好并返回正确的数据,我认为问题一定出在客户端。

谢谢。

【问题讨论】:

    标签: angularjs ngresource


    【解决方案1】:

    $scope.pages 不是数组。所以你得到了这个错误。您必须将其指定为数组,然后您可以将任何值推送到该数组。

    试试这个方法。

            $scope.pages=[];    
            var idx = $scope.pages.push(newItem).length-1;
            $scope.pages[idx].active = true;  
    

    也看到这一行

    var idx = $scope.pages.push(newItem).length-1;

    【讨论】:

    • 嗨拉梅什,谢谢您的回答。我使用此代码从服务器加载我的模型。在 Chrome 调试器中 res 是一个数组。:
    • Page.query(function(res) { $scope.pages = res; }, function(error) {});
    • 顺便说一句,服务器从 $save 返回时出现错误。如果我(在响应中)返回一个空的 JSON 数组,那么只有当我返回新记录时才会出现错误。但是我需要以某种方式取回保存的数据以更新客户端模型,因为我在服务器端对其进行了修改。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    相关资源
    最近更新 更多