Angular ui-router's nested routes not working

2019-07-11 21:42发布

问题:

I have multiple modules in Angular and I also use nested routes. There is an auth module which also has a sub route auth.login the code goes as follows:-

Login.route.js

routes.$inject = ['$stateProvider'];

export default function routes($stateProvider) {
    $stateProvider
        .state('auth.login', {
            url: '/login',
            template: require('./login.tpl.html')
        });
}

auth.route.js

routes.$inject = ['$stateProvider'];

export default function routes($stateProvider) {
    $stateProvider
        .state('auth', {
            url: '/auth',
            template: require('./auth.tpl.html')
        })
}

Then inject these into the main module like this according to the folder structure.

import auth from './features/auth';
import auth from './features/auth/login';

I am not getting any error but apart from the / & /auth path nothing reflects. If I use /login it redirects me to the / path.

Kinda weird but UI-Router is not working. Please suggest.

NOTE: I use BableJS and Webpack for the Development

回答1:

I noticed that the code you've shown never actually invokes the exported functions. That might be the root of your problem.

A better way to approach this might be to export the state objects themselves. In the outermost file, you can then import those state objects, and register them with the $stateProvider. Here's an example:

Login.route.js

let loginState = {
  // UI-Router allows state definitions to contain the name
  name: 'auth.login', 
  url: '/login',
  template: require('./login.tpl.html')
}

// Just export the state definition; you don't have to register it yet
export default loginState;

auth.route.js

let authState = {
  name: 'auth',
  url: '/auth',
  template: require('./auth.tpl.html')
}
export default authState;

app.js

This file shows bootstrapping the application. It imports the state definitions from the child modules, and registers them with the $stateProvider.

// Now import the state definitions from the other modules
import loginState from './Login.route.js';
import authState from './auth.route.js';

let app = angular.module('app', ['ui.router']);
// create a single config block which registers 
// all the state definitions that were imported
app.config(registerAllStates);

registerAllStates.$inject = ['$stateProvider'];
function registerAllStates($stateProvider) {
  // Loop over them and register them with the $stateProvider.
  [loginState, authState].forEach(state => $stateProvider.state(state));
}