RobSeg
RobSeg

Reputation: 1035

How to redirect in Angular if translate cookie is not set?

I want to redirect the user to a language page and not allow him to the index page if he hasn't chosen a language yet. I'm using the Angular Translate module. This module has cookie usage built-in with the following function:

$translateProvider.useCookieStorage();

This works. Now I would like to know if this cookie is set, and if not, redirect the user to the language page. Here's my idea how to handle this.

.factory('cookiecheck', function(){
  if($translateProvider.CookieStorage.get) return true;
  return false;
}


.run(function($rootScope, $state){

if(cookiecheck
            {$location.path('/language');}
    else
            {$location.path('/home');}

This doesn't work. How would I best approach this? What is the correct syntax to determine if a CookieStorage exists and redirect?

Upvotes: 1

Views: 1509

Answers (1)

Dane Macaulay
Dane Macaulay

Reputation: 814

You have a few syntax errors in your posted code, the factory isn't necessary as you can inject the $translate service into your run block.

.run(function($rootScope, $state, $location, $translate) {
    var store = $translate.storage();
    // if store is empty?
    if(angular.equals(store, {}))){
        $location.path('/language');
    }
    else {
        $location.path('/home');
    }
});

See ng-translate docs for cookie store

Also, since you won't know if and when the cookie will be expired or removed i think it is best to watch the route for changes and do your check then.

To do that hook into the $stateChangeStart event from ui router in your run block

    $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){
        // check then redirect
    });

ui router docs

see this post for watching route changes

Upvotes: 1

Related Questions