0

I'm building my first angular app and many of the major features are separated into their own modules. Each module registers its routes in config with $stateProvider.

I want to be able to handle $stateChangeStart/$stateChangeError in one place for my whole app so I can evaluate authorization and handle errors. How do I do this?

Currently I have this handler registered on $rootScope on my main module/app but if I navigate to a route from another module and then navigate to another route it does not fire. Why? In fact even $urlRouterProvider.otherwise("xyz"); no longer works.

I don't like copy pasting code so any solution that avoids putting this logic in every module would be appreciated.

Justin_H
  • 407
  • 5
  • 19

1 Answers1

0

You can try something like:

var app = {};

// Route Config for a "some" module.
function someModuleConfig($stateProvider) {
  $stateProvider.
      state('something', {
        url: '/something',
        templateUrl: 'path/to/something/something.html',
      });
}

// Module definition for "some" module.
app.somemodule.module = angular.module('app.somemodule', []).
    config(someModuleConfig);

// Route Config for the main module.
function appConfig($stateProvider, $urlRouterProvider) {
  // Set the default redirect for any missing route.
  $urlRouterProvider.otherwise('xyz');

  $stateProvider.
      state('home', {
        url: '/',
        templateUrl: 'path/to/home/home.html'
      });
};

// Module definition for the main module.
app.module = angular.module('myapp', [
  'ui.router',
  app.somemodule.name
]).config(appConfig);

The key is that you can register your routes with the main module, and subroutes can be registered in other modules. You could also register all your routes in the main app module as well, depending on how you structure your code.

User 1058612
  • 3,739
  • 1
  • 27
  • 33
  • Thanks Johnny, This is essentially what I have except I additionally register my state change handlers in the run method on the main module. I'm still getting this error though without either handler ever firing: Error: Could not resolve 'welcome' from state 'newuser.accountsetup' (both states in error message are from another module.) – Justin_H Oct 07 '15 at 20:50
  • If you you are registering the state change handling logic in the `run` block, then this SO [link](http://stackoverflow.com/a/20664122/1058612) might be helpful, and the link it references ([here](http://arthur.gonigberg.com/2013/06/29/angularjs-role-based-auth/)), might be even more useful. It looks like the 2nd link describes how you might want to handle the state change. – User 1058612 Oct 07 '15 at 21:00
  • figured it out: the default route you give in $urlRouteProvider.otherwise('xyz') is scoped just to the module. However you can just listen for '$stateNotFound' on $rootScope in the main module and redirect from there to create a global default state. That is what I was missing. – Justin_H Oct 08 '15 at 01:32