当我从另一个文件尝试调用函数时,我收到错误:
app.js中的TypeError:无法读取未定义
的属性'getCurrentUserFullName'
:
'use strict';
var testApp = {};
var App = angular.module('testApp', ['testApp.filters', 'testApp.services', 'testApp.directives',
'ngRoute']);
App.run(['$location', '$rootScope', function ($location, $rootScope) {
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils) {
if(!$rootScope.userFullName){
var userFullName = AuthUtils.getCurrentUserFullName();
if(userFullName) {
$rootScope.userFullName = userFullName;
$rootScope.authenticate = true;
} else {
$rootScope.authenticate = false;
$rootScope.userFullName = "";
}
}
});
}]);
AuthUtils.js
'use strict';
angular.module('testApp')
.factory('AuthUtils', function AuthUtils($rootScope, $http) {
return {
getCurrentUserFullName: function () {
$http.get('auth/userFullName').success(function (user) {
return user;
}).error(function (data, status) {
return "error";
console.error(status, data);
});
}
};
});
为什么不起作用?
答案 0 :(得分:2)
您错过了在AuthUtils
区块内注入run
。注入它,以便工厂块中的工厂实例可用
App.run(['$location', '$rootScope', 'AuthUtils', //<== injected AuthUtils here
function ($location, $rootScope, AuthUtils) { //<== and here
另外,您需要从AuthUtils
函数中删除$routeChangeSuccess
参数,这会导致在运行块中存在已注入的AuthUtils
。
更改为
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) //<--removed AuthUtils
这
$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils)