2014-12-21 25 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 **/ } 
);