2014-12-21 30 views
6

我使用restangular PUT方法,但是我有一个“放”的方法出了问题,它不是按预期工作如何使用restangular

我angularService代码

var userService = function (restangular) { 
      var resourceBase = restangular.all("account/"); 

      restangular.addResponseInterceptor(function (data, operation, what, url, response, deferred) { 
       if (operation == "getList") { 
        return response.data; 
       } 
       return response; 
      }); 
     this.getUserById = function (id) { 

       return resourceBase.get(id); 
       // return restangular.one("account", id).get(); 
      }; 
      this.updateUser = function(user) { 
       return user.Put(); 
      }; 
} 

我的控制器代码

var userEditController = function (scope, userService, feedBackFactory, $routeParams) { 

     scope.user = undefined; 

     scope.updateUser = function() { 

      userService.updateUser(scope.user).then(function (data) { 
       feedBackFactory.showFeedBack(data); 
      }, function (err) { 
       feedBackFactory.showFeedBack(err); 
      }); 
     }; 

     userService.getUserById($routeParams.id).then(function (data) { 
      scope.user = data.data; **// Please not here I am reading the object using service and this object is getting updated and pass again to the service for updating** 

     }, function (er) { 

      feedBackFactory.showFeedBack(er); 
     }); 

    }; 

但我得到一个错误“放”不是一个函数,我检查了用户对象,我发现用户对象没有重新调整(没有任何额外的方法fo UND)。我该如何解决它

回答

2

你可以把方法只在restangularized对象。要对任何对象进行触发,您需要检查put方法,如果对象不包含任何put方法,则需要将该对象转换为restangularized对象。

您UpdateUser两个更改为以下几点:

this.updateUser = function(user) { 
    if(user.put){ 
     return user.put(); 
    } else { 
     // you need to convert you object into restangular object 
     var remoteItem = Restangular.copy(user); 

     // now you can put on remoteItem 
     return remoteItem.put(); 
    } 
}; 

Restangular.copy方法会增加一些额外的restangular方法为对象。简而言之,它会将任何对象转换为重新激活的对象。

+0

你怎么让它知道类型是'user'?例如,当使用'copy()'方法时,我得到'http:// localhost:8100/api/undefined'。 'undefined'应该是'user'对象。如何使它正确?谢谢! –

10

您只能'放入'数据对象。

customPUT([elem, path, params, headers])是你想要的。像这样使用它:

Restangular.all('yourTargetInSetPath').customPUT({'something': 'hello'}).then(
    function(data) { /** do something **/ }, 
    function(error) { /** do some other thing **/ } 
);