[英]Unable to inject Services in .run in angular js
我想将服务注入到我的.run
块中,但是当我注入它时,我将无法使用它们。
我的代码是:
.run(['AuthFactory', function ($state, $rootScope, AuthFactory, $location) {
console.log("Auth Factory :%O", AuthFactory);
AuthFactory.registerUserChangeHandler(function (currentUser) {
$rootScope.currentUser = currentUser;
});
AuthFactory.refresh().then(function (currentUser) {
console.log("Current User is", currentUser);
}, function (reason) {
// User is not Logged in
$location.path("login");
});
}]);
当我编写此代码时,出现错误:
“ app.js:120Uncaught TypeError:无法读取未定义的属性'registerUserChangeHandler'
如果我只是在函数中注入AuthFactory
,那么一切正常,但是现在我想在服务内部注入UserService
和使用方法。
我尝试将其注入功能中,但无法使用。
打开所有建议。
你搞砸了DI。
.run(['state', '$rootScope', 'AuthFactory', '$location',
function ($state, $rootScope, AuthFactory, $location) {
console.log("Auth Factory :%O", AuthFactory);
// ...
}]);
错误是,如果您使用数组注入的方式进行依赖注入,则需要遵循顺序。 例如,如果$ state是数组中的第一个值,则在控制器回调中,第一个值将表示$ state。
.run(['$state','$rootScope','AuthFactory','$location', function ($state, $rootScope, AuthFactory, $location) {
console.log("Auth Factory :%O", AuthFactory);
// UserService.login({
// 'username': "guest",
// 'password': "guest"
// }, function () {
// $state.go("corporate_site.home", {reload:'true'});
// }, function () {
// $rootScope.error = "Login Failed. Invalid Credentials.";
// });
// $state.go("corporate_site.home", {reload: 'true'});
AuthFactory.registerUserChangeHandler(function (currentUser) {
$rootScope.currentUser = currentUser;
});
AuthFactory.refresh().then(function (currentUser) {
console.log("Current User is", currentUser);
}, function (reason) {
// User is not Logged in
$location.path("login");
});
}]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.