javascript Angular JS:$location 注入未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19670220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular JS: $location injection undefined
提问by Dario
I'm trying to configure my route in such a way to redirect to the login page if user is not logged. This is my code:
如果用户未登录,我正在尝试以这种方式配置我的路由以重定向到登录页面。这是我的代码:
angular.module('witBiz.services', []);
angular.module('witBiz.controllers', ['witBiz.services']);
var witBizModule = angular.module('witBiz', ['ngRoute' , 'witBiz.controllers', 'witBiz.services' ]);
witBizModule.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/login', {templateUrl: 'resources/views/login.html', controller: 'LoginController'});
$routeProvider.when('/index', {templateUrl: 'resources/views/index.html', controller: 'IndexController'});
$routeProvider.otherwise({redirectTo: 'resources/views/index.html'});
}])
.run(['$rootScope', 'checkLogin', function($rootScope, checkLogin ,$routeProvider ) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/index");
})
}])
.factory('checkLogin', function(){
return function() {
//perform real logic here
return true;
}
})
where basically I declare modules and services. Now the problem is $location is not defined so I get error. I tried to inject $location as dependency like this but I got undefined injection (injpt):
基本上我在这里声明模块和服务。现在的问题是 $location 没有定义所以我得到错误。我试图像这样注入 $location 作为依赖项,但我得到了未定义的注入(injpt):
.run(['$rootScope', 'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/ciao");
})
}])
So I'm wondering how I can use the builtin $location services inside my "run" method...why can I inject it as a dependency as $rootScope or checkLogin?!
所以我想知道如何在我的“运行”方法中使用内置的 $location 服务......为什么我可以将它作为依赖项注入 $rootScope 或 checkLogin?!
I'm using angular 1.2.0 rc2.
我正在使用 angular 1.2.0 rc2。
Thanks
谢谢
回答by bekite
Here is a working example http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview
这是一个工作示例http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p=preview
Couldn't reproduce the error with $location not working inside .run
无法重现 $location 在 .run 中不起作用的错误