AngularJS从另一个文件调用函数

时间:2016-03-17 21:22:56

标签: angularjs

当我从另一个文件尝试调用函数时,我收到错误:

  

TypeError:无法读取未定义

的属性'getCurrentUserFullName'
app.js中的

    '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);
                    });
                }
            };
        });

为什么不起作用?

1 个答案:

答案 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)