角度"$.ajax"有效,但"$resource" - 抛出错误如何解决这个问题?



在我的应用程序中,我正在尝试向服务器发送请求POST。为此,我使用$resource模块。然而,当我试图发布对象时,我得到了一个错误TypeError: server.batchUpdate.save(...).$promise is not a function,我根本无法发布。。

这是代码:

$scope.batchUpdate = function ( object ) {
        var newId = Number(object.Id);
        var newType = 'project';
        var newImportant = !object.IsImportant;
        var newobject = {
            "Id" : newId,
            "Type" : newType,
            "IsImportant"  : newImportant
        }
        console.log( newImportant, newId ); //updates
        server.batchUpdate.save({
            "updateImportant" :  JSON.stringify(newobject)
        })
        .$promise().then(function ( response ) {
            cosole.log( response );
        });
    }

我试过了,但根本无法解决这个问题。后来我尝试使用直接jQuery ajax方法,效果很好。这是代码:

$scope.batchUpdate = function ( object ) {
        var newId = Number(object.Id);
        var newType = 'project';
        var newImportant = !object.IsImportant;
        var newobject = {
            "Id" : newId,
            "Type" : newType,
            "IsImportant"  : newImportant
        }
        var param = { "updateImportant":newobject };
        $.ajax({
           type: "POST",
           url: "http://azvsptcsdev02:678/_vti_bin/CPMD.WEBSERVICE/ProjectInfoService.svc/UpdateImportantbyUser",
           data: JSON.stringify(param),
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           processData: true,
           success: function (data, status, jqXHR) {
               console.log("success" + data, status, jqXHR ); /*getting response*/
           },
           error: function (xhr) {
               console.log('failure', xhr.responseText);
           }
       });

    }

但我更喜欢使用$resource方式。我需要如何处理我的$resource帖子?有人帮我吗?

问题是您试图将.$promise用作函数而不是属性。下面是您应该看到的样子,注意.$promise不是被调用的,而是被访问的(没有括号)。

$scope.batchUpdate = function (obj) {
    var newId = Number(obj.Id);
    var newType = 'project';
    var newImportant = !object.IsImportant;
    var newobject = {
        "Id" : newId,
        "Type" : newType,
        "IsImportant"  : newImportant
    };
    console.log(newImportant, newId); // Updates
    server.batchUpdate.save({
        "updateImportant" :  JSON.stringify(newobject)
    })
    .$promise.then(function(response) {
        cosole.log(response);
    });
}

最新更新