Search code examples
angularjsangular-resourceangularjs-resource

Use dynamic parameters in Angular Resource


the Angular-Resource documentation says for parameters:

If any of the parameter value is a function, it will be executed every time when a param value needs to be obtained for a request (unless the param was overridden).

Unfortunately this does not work for me, the function is only called once when the resource is initialized.

My case: I have a global Application state which you can choose on the top navigation of the app. This state affects a query param in most calls. (e.g. the date for which the call is valid). I maintain this global state in a service.

My Services (model layer) look like this:

function($resource, ApplicationState) {
      return $resource('test/:_id', {
        date: ApplicationState.getCurrentTime()
      }, {
        get: {
          method: 'GET'
        }
      });
    }

I'd expect ApplicationState.getCurrentTime() to be called on every get call. It is only called once.

I created a plunkr as an example. Open the Browsers Debug Console to see that ApplicationState.getCurrentTime() is only called once and not every time you click on the button.

http://plnkr.co/edit/qeoIUuzFCqnQNdnYp5ZX?p=preview

What do I do wrong? Is there a better way to inject dynamic parameters to some resources? I know the concept of request intereceptors, but I need this only on some services and not all.

Thanks for your help!


Solution

  • I found the answer with the help of frfancha on Github, the trick is to pass the function itself and not the result of the function.

    See the missing brackets after ApplicationState.getCurrentTime here:

    function($resource, ApplicationState) {
      return $resource('test/:_id', {
        date: ApplicationState.getCurrentTime
      }, {
        get: {
          method: 'GET'
        }
      });
    }
    

    The function is now evaluated every time a request is made.

    An updated Plnkr can be found here: http://plnkr.co/edit/Qx9HSsFwt5LDiM6Vmgff?p=preview Credits go to frfrancha on Github