Search code examples
restangular

Change the route for a Restangular object


I'm using Restangular to login my currentUser like this:

  this.login = function (credentials) {

    var loginURL = Restangular.all('logins');

    return loginURL.customPOST({ user: credentials.user, password: credentials.password })
      .then(function (res) {
         $scope.currentUser = res;
         console.log("User successfully logged in.");
      };
   };

At some point the currentUser might need to update his preferences with a customPUT() . . .

  this.updateUser = function(currentUser){

    return currentUser.customPUT({ user: currentUser })
      .then(function(response){
        if (typeof response.errors === 'undefined') {
          $rootScope.$broadcast(AUTH_EVENTS.updateAccount, response.data );
          console.log("Account successfully updated.");
          currentUser = response.data
        } else {
          $q.reject(response);
        }
      }, function(response){
        $q.reject(response);
      });

My problem is that my server api has a one route for logins/outs (/api/logins/) and a different route for user updates (/api/users/).

Is there a way to easily change the route on my currentUser object after login so that it uses the /api/users route?


Solution

  • I assume

    • that you have set the baseUrl (via Restangular.setBaseUrl) to your API
    • and that the route 'users' is needed most of the time.

    If this is true, one solution would be to take the plain object returned by the login and re-restangularize it. This can look similar to following code:

        $scope.currentUser = res.plain();
        Restangular.restangularizeElement('', $scope.currentUser, 'users');
    

    Try this in the then-part of your login POST. Afterwards $scope.currentUser should be your user object, but all set up like you've retrieved it from /users. Subsequent REST-operations will then use the new URL.