如何在restangular中使用PUT方法

Bin*_*ose 6 javascript angularjs restangular

我正在使用restangular,但我有"Put"方法的问题,它没有按预期工作

我的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();
            };
}
Run Code Online (Sandbox Code Playgroud)

我的控制器代码

 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);
        });

    };
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误"Put"不是一个函数,我检查了用户对象,我发现用户对象没有被重新调整(没有找到任何其他方法).我该怎么解决呢

小智 10

你只能'放'一个数据对象.

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

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


dha*_*ngg 2

您只能在重新角度化的对象中使用 put 方法。要在任何对象上触发 put,您需要检查 put 方法,如果对象不包含任何 put 方法,那么您需要将该对象转换为重新角度化的对象。

将您的 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();
    }
 };
Run Code Online (Sandbox Code Playgroud)

Restangular.copy 方法将在对象中添加一些额外的 Restangle 方法。简而言之,它将任何对象转换为重新角度化的对象。