如何编写具有自己路由的不同模块?
我有一个 Angular 应用程序,它有不同的模块。我要为每个模块编写特定的路由文件,但我收到了此错误
Uncaught Error: [$injector:unpr] http://errors.angularjs.org/1.6.4/$injector/unpr?p0=routeServiceProvider%20%3C-%20routeService
这是我的代码:
示例.module.js
angular.module('app.sample', []);
示例.route.js
angular
.module('app.sample')
.run(appRun);
/* @ngInject */
function appRun (routeService) {
routeService.configureRoutes(getRoutes());
}
function getRoutes () {
return [ {
url: '/sample',
config: {
templateUrl: 'sample.html'
}
}
];
}
我已经添加了 ngRoute 并将这些文件注入(inject)到 index.html
文件中
最佳答案
为了实现这样的项目结构,ui-router是最好的方法。它是一个单独的库,因此您必须将其作为依赖项包含到您的项目中。
以下是对您的案例有用的片段
仪表板.module.js
angular.module('app.dashboard', ['ui.router']);
仪表板.router.js
angular.module('app.dashboard')
.config(routerConfig);
routerConfig.$inject = ['$stateProvider'];
function routerConfig($stateProvider) {
$stateProvider
.state('state1', {
url: '/state1',
templateUrl: 'url/to/state1.html',
controller: function () {
// controller code here
}
})
.state('state2', {
url: '/state2',
templateUrl: 'url/to/state2.html',
controller: function () {
// controller code here
}
});
}
示例.module.js
angular.module('app.sample', ['ui.router']);
示例.router.js
angular.module('app.sample')
.config(routerConfig);
routerConfig.$inject = ['$stateProvider'];
function routerConfig($stateProvider) {
$stateProvider
.state('state3', {
url: '/state3',
templateUrl: 'url/to/state3.html',
controller: function () {
// controller code here
}
})
.state('state4', {
url: '/state4',
templateUrl: 'url/to/state4.html',
controller: function () {
// controller code here
}
});
}
最后,app.module
连接所有这些模块
app.module.js
angular.module('app', [
/*
* sub-modules
*/
'app.dashboard',
'app.sample'
]);
总而言之,您有两个独立的子模块(app.dashboard
和 app.sample
),它们拥有自己的路由逻辑和一个模块(app
)将它们包装到一个 Angular 应用程序中。
$stateProvider
,由ui.router
提供的服务,用于注册状态。
其他信息
由于您的应用程序是模块化的,因此您可能需要 ui.router
大力支持的嵌套路由。阅读 docs获取有关嵌套状态的更多信息。
更新
关于angularjs - Angular 路由子模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397113/