pro.mean pro.mean - 4 months ago 64
AngularJS Question

angular ui-router logout state doesn't redirect to login until refresh the page

What I need that on click on logout link ,

we call logout method of the AuthService to clear cookie data and than user should redirected on login page.

But it seem's not working. page being stay on /logout page and user need to refresh the page than it goes to /login page. why so?

here is my relevant code

.state("logout", {
url: '/logout',
data: {
requiresAuth: true
},
controller:['$state', 'AuthService', function($state, AuthService) {
AuthService.logout();
$state.transitionTo('login', null, { reload :true});
}]
})


and here is relevant AuthService method

app.factory('AuthService', function($log, $http, $q, $cookies){
authService.logout = function () {
var deferred = $q.defer();
$http({
method: "GET",
url: '/app/logout.json'
}).then(function(result) {
$cookies.remove('currentUser');
deferred.resolve(result);
}, function(error) {
deferred.reject(error);
});
return deferred.promise;
};
});


Note : when I write /logout in URL and hit it than it goes to login page.

Answer

Is your factory code complete as posted? If yes, I am afraid you have syntax error. This is because authService will be undefined.

You will have to first declare the authService as an object, and then return that object in your factory function. Else, your AuthService service will go haywire when injected.

app.factory('AuthService', ['$log', '$http', '$q', '$cookies', function($log, $http, $q, $cookies) {
  //declare your authService variable first, as an object.
  var authService = {};
  //now you are declaring a method inside this object,named logout
  authService.logout = function() {
    var deferred = $q.defer();
    $http({
      method: "GET",
      url: 'logout.json'
    }).then(function(result) {
      $cookies.remove('currentUser');
      deferred.resolve(result);
    }, function(error) {
      deferred.reject(error);
    });
    return deferred.promise;
  };
  //remember to return this object so that it can be used as a service
  return authService;
}])

I have pretty much mocked an example as closely and as relevant as your code. It works fine. Here is the plnkr.

One gentle reminder though: at the controller of your logout state, you would want to only do $state.transitionTo AFTER AuthService has been resolved. Something like this:

AuthService.logout().then(function() {
  $state.transitionTo('login', null, {
    reload: true
  });
},function(){
  //handle error here
})

I did not change that in the plnkr, since this is your app and you should be clear with what you are achieving.

Comments