Search code examples
angularjsangular-resource

Resources with Parameter, How to update the parameters on login?


I'm writing an angular 1.6.9 application that uses Resources to communicate with a REST PHP Backend.

Resources have some parameters:

angular.module('app').factory('BookResource', function($resource, $localStorage) {
  return $resource('/rest/:roleId/ul/:ulId/book/:id',
    {
      roleId: $localStorage.currentUser.roleId,
      ulId  : $localStorage.currentUser.ulId,
      id    : '@id'
    }, {
    update: {
      method: 'PUT' // this method issues a PUT request
    }
  });
});

Here you can see that I'm using two parameters that are taken from the local storage.

Everything works fine, except when there's a change of user in the same browser window. When logging back in, the REST Call are made with the previous values of the parameters, not the new values stored in the $localStorage (which is cleared on logout and login).

A SHIFT+REFRESH do fix the issue, but I was wondering if I could avoid asking users to do SHIT+REFRESH at each user change, which will happen.

A workaround is to ask them to systematically uses private navigation, but I'm pretty sure some won't and will complain ;)

So is there some way to programmatically go through each Resources and update them when login?


Solution

  • Use a function:

    app.factory('BookResource', function($resource, $localStorage) {
      return $resource('/rest/:roleId/ul/:ulId/book/:id',
        {
          roleId: function () { return $localStorage.currentUser.roleId },
          ulId  : function () { return $localStorage.currentUser.ulId },
          id    : '@id'
        }, {
        update: {
          method: 'PUT' // this method issues a PUT request
        }
      });
    });
    

    From the Docs:

    If a parameter value is a function, it will be called every time a param value needs to be obtained for a request.

    — AngularJS $resource API Reference - arguments