Monday, January 16, 2017

Angular Factory for $resource and dynamic header content

I created a Factory recipe for my $resource instance.

There are multiple ways to create it. I used this approach.

  angular.
    module('myModule').
    factory('myService', ['$resource', '$localStorage',
      function($resource, $localStorage) {
        var url = 'xxx';
        return $resource(url + '/my-resource/:id', { id: '@id'}, {
          query: {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'X-Auth-Token': $localStorage.token
            },
            isArray: true
          },
 ...
]);
It was working fine till I notice this issue.

If I logout and login as different user the old token was being used!!!

This is because the Service and Factory instances are Singleton. On logout we clear data and not the object of the app in the browser. The first value of $localStorage.token is used to create the instance and that does not get updated even when the value $localStorage.token changes.

One approach to fix this would be create 
  angular.
    module('myModule').
    factory('myService', ['$resource', '$localStorage',
      function($resource, $localStorage) {
        var url = 'xxx';
return { GetInstance: GetInstance };
function GetInstance(token) {
        return $resource(url + '/my-resource/:id', { id: '@id'}, {
          query: {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'X-Auth-Token': token
            },
            isArray: true
          },
}
 ...
]);

In the controller  myService.GetInstance( $localStorage.token).query()

This is more work.

The better approach would be to get the 'X-Auth' dynamically. This can be achieved by using a function instead of value.

angular.
    module('myModule').
    factory('myService', ['$resource', '$localStorage',
      function($resource, $localStorage) {
        var url = 'xxx';
function GetToken() {
 return $localStorage.token;
}
        return $resource(url + '/my-resource/:id', { id: '@id'}, {
          query: {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
              'X-Auth-Token': GetToken
            },
            isArray: true
          },
 ...
]);