尝试创建自定义提供商并在应用程序配置期间使用它。在配置阶段得到一个错误"由于未知的提供商'configRoutesProvider',无法实例化模块应用"。提供者代码:
(function () {
'use strict';
angular.module('app-routing', [])
.provider('configRoutesProvider', function () {
this.$get = ['$http', getRoutesProvider];
function getRoutesProvider($http) {
return {
getRoutes: function ($http) {
return $http.get('https://localhost:44311/api/account/routes').then(function (results) {
return results;
});
}
};
}
});
}).call(this);
在app.js代码中获取对'app-routing'模块的引用:
(function () {
'use strict';
var app = angular.module('app',
[
'ngRoute', // routing
'LocalStorageModule', // local storage
'app-routing'
]);
app.run();
})();
在config.js中,当试图引用提供程序时,会得到上面的错误:
app.config(['$routeProvider', 'configRoutesProvider', routeConfigurator]);
function routeConfigurator($routeProvider, configRoutesProvider) {
var routes = configRoutesProvider.getRoutes();
routes.forEach(function (r) {
$routeProvider.when(r.href, {
controller: r.controller,
templateUrl: r.templateUrl
});
});
$routeProvider.otherwise({ redirectTo: '/home' });
}
在index.html中脚本注册的顺序如下:
<script src="app/routesProvider.js"></script>
<!-- Load app main script -->
<script src="app/app.js"></script>
<script src="app/config.js"></script>
不明白我错过了什么?
在angular中,providers的名字中没有provider
部分,所以我们的想法是:
angular.module('foo').provider('configRoutes', function() { });
而不是:
angular.module('foo').provider('configRoutesProvider', function() { });
但是当你把它注入到配置中时,你必须把它放在:
angular.module('foo').config(function(configRoutesProvider) { });
因此,在您的示例中,删除定义上的provider
部分。
文件: route.js
var appRoutes = angular.module('appRoutes',['ngRoute'])
appRoutes.config(function($routeProvider,$locationProvider){
$routeProvider
.when('/',{
templateUrl: 'app/views/pages/home.html'
})
.when('/about',{
templateUrl: 'app/views/pages/about.html'
})
.otherwise({ redirectTo: '/'});
console.log('Testing routes routes...');
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
});
});
其作品。这是在route.js文件中定义路由的另一种方式。这里我给出了正确的路径,并使用了$routeProvider, $locationPRovider, ngroute