2014-12-21 10 views
6

Sto usando restangular, ma ho un problema con il metodo "put", il suo non funziona come previstoCome utilizzare il metodo PUT in restangular

Il mio codice 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(); 
      }; 
} 

Il mio codice di controllo

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

    }; 

ma sto ricevendo un errore "Put" non è una funzione, ho controllato l'oggetto utente e ho trovato che l'oggetto utente non è restangularizzato (nessun metodo aggiuntivo per und). Come posso risolverlo

risposta

2

Puoi mettere il metodo solo negli oggetti restangolarizzati. Per attivare un oggetto, è necessario verificare il metodo put, se l'oggetto non contiene alcun metodo put allora è necessario convertire quell'oggetto in oggetto restangularizzato.

Cambia la tua UpdateUser a seguire:

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

metodo Restangular.copy aggiungerà alcuni metodi restangular in più in oggetto. In breve, convertirà qualsiasi oggetto in un oggetto restangularizzato.

+0

Come hai fatto sapere che il tipo è 'utente'? per esempio, ottengo 'http: // localhost: 8100/api/undefined' quando si usa il metodo' copy() '. Il 'undefined' dovrebbe essere l'oggetto' utente'. Come farlo bene? Grazie! –

10

È possibile solo "inserire" un oggetto dati.

customPUT([elem, path, params, headers]) è quello che vuoi. usalo in questo modo:

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