Search code examples
angularjsangularjs-injector

Angular function is not using explicit annotation and cannot be invoked in strict mode


In my web application I want to verify if the user has the permissions to continue.

This is the .run method in my index.js file:

  .run(function (event, toState, toParams, fromState, $window) {
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, $window) {
  if (Auth.isLoggedIn && $window.localStorage.identityToken) {

    var requiredAdmin = toState.data.requiredAdmin; 
    if (requiredAdmin && $window.localStorage.isAdmin){
      $state.go(toState.name);
    } else {
      $state.go(fromState.name);
    }
    var shouldGoToMain = fromState.name === 'login' && toState.name !== 'app.dashboard' ;

    if (shouldGoToMain){
      $state.go('app.dashboard');
      event.preventDefault();
    } else {
      $state.go(toState.name);
    }
    return;
  } else { 
    $state.go('login');
    return;
  }

  // unmanaged
});

});

The console error is: Uncaught Error: [$injector:strictdi] function(event, toState, toParams, fromState, $window) is not using explicit annotation and cannot be invoked in strict mode


Solution

  • You enabled strict mode, in order to detect where you forgot to use $inject or the array notation to make sure your code can be safely minified.

    The message tells you that you failed to properly annotate your injectable functions. Note that, in addition to that, your code doesn't make much sense:

    • the function passed to run() is supposed to take injectable services as argument, and all its arguments except $window are not services.
    • the function passed to $on() is not an injectable function. So passing it $windows makes no sense. The router will only invoke it with the 4 first arguments.

    So, your code should be:

    .run(['$rootScope', '$window', function($rootScope, $window) {
        $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState) { 
    

    I would strongly advise to stop annotating your injectable functions by hand, and to use ng-annotate to do that for you.