Angular JS:$位置注入未定义 [英] Angular JS: $location injection undefined
问题描述
我正在尝试以这种方式配置路由,以便在用户未登录的情况下重定向到登录页面.这是我的代码:
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;
}
})
基本上,我在其中声明模块和服务.现在的问题是未定义$ location,所以我得到了错误.我试图像这样将$ location注入为依赖项,但是我得到了未定义的注入(injpt):
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):
.run(['$rootScope', 'checkLogin', '$location', function($rootScope, checkLogin ,$location) {
$rootScope.$on('$routeChangeSuccess', function () {
if (checkLogin())
$location.url("/ciao");
})
}])
所以我想知道如何在我的运行"方法中使用内置的$ location服务...为什么要把它作为依赖项注入$ rootScope或checkLogin?!
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?!
我正在使用角度1.2.0 rc2.
I'm using angular 1.2.0 rc2.
谢谢
推荐答案
这是一个有效的示例 http://plnkr.co/edit/gf5LhTjqhz4MoZfVcqIt?p = preview
由于$ location在.run内部无法正常工作,因此无法重现错误.
Couldn't reproduce the error with $location not working inside .run
这篇关于Angular JS:$位置注入未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!