【问题标题】:How to use PUT method in restangular如何在restangular中使用PUT方法
【发布时间】:2016-05-11 15:26:40
【问题描述】:

我正在使用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();
            };
}

我的控制器代码

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

    };

但我收到错误“Put”不是函数,我检查了用户对象,发现用户对象没有重新调整角度(没有找到任何其他方法)。我该如何解决它

【问题讨论】:

    标签: javascript angularjs restangular


    【解决方案1】:

    您只能“放置”一个数据对象。

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

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

    【讨论】:

      【解决方案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();
          }
       };
      

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

      【讨论】:

      • 你怎么让它知道类型是user?例如,我在使用copy() 方法时得到http://localhost:8100/api/undefinedundefined 应该是 user 对象。如何使它正确?谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 2021-07-29
      相关资源
      最近更新 更多