Chris Chris - 6 months ago 29
AngularJS Question

The ui-router for angular seems to be cacheing the resolve. When I don't want it to

The Background:

I am using ui-router for my Angular page routing needs. It's working great so far, however I'm running into an issue. When I load a state and I resolve my user object. I use restangular to make the call to the database and it returns a promise. Everything works great. If I then log out, and log in as another user. Then navigate back to that same page it shows the previous user object.

Things that I've discovered:


  • The rest api call is being made every time when the state loads, and
    it is the correct information.

  • If I place a break point inside my controller the user object that the resolve passes is the cached
    information.



Theories:


  • The rest API end point is /users/me/, which is the same end point for
    every user. We just deliver different information based off of the
    JWT token we pass. Somewhere must things since it's the same call
    don't bother delivering the goods it already got.



Things I've tried:


  • I've confirmed that the API call isn't cached, and it is delivering
    the correct information to angular

  • I've tried grabbing the
    $cacheFactory of $http and .removeAll.



Sample code:

angular.module('services.user', [ ])
.factory('User', function(Restangular) {
return Restangular.service('users');
});

angular.module('settings.profile', [
'ui.router',
'services.user'
])

.config(function($stateProvider){
$stateProvider
.state('settings.profile',{
url: '/profile',
templateUrl: 'app/settings/profile/settings.profile.html',
controller: 'SettingsProfileCtrl',
authenticate: true,
resolve: {
user: function(User) {
var user = User.one('me').get()
return user;
}
}
});
})

.controller('SettingsProfileCtrl',
function($scope, $location, user, $http, apiUrl){

$scope.user = user;
}

Answer

Your REST API parameter does not change i.e. it stays the same /users/me/ in all the requests. While the browser may not cache - which is why you see different correct information the cache.

You can try configuring Restangular to validate the theory by doing as below:-

RestangularProvider.setDefaultHttpFields({cache: true});

However I advise you to use URLs and REST API in the spirit of REST style i.e. use something like...

/users/me/username

where username changes based on the user OR if you have some constraints do the following

/users/me/?t=timestamp