2016-03-17 20 views
1

當我從另一個文件試圖通話功能,我得到錯誤:AngularJS從另一個文件調用函數

TypeError: Cannot read property 'getCurrentUserFullName' of undefined

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

爲什麼不起作用?

回答

2

您錯過了在run區塊內注入AuthUtils。注入這麼工廠實例Additonally你需要從$routeChangeSuccess功能,這是在運行塊殺死注入AuthUtils的存在刪除AuthUtils參數是運行程序段

App.run(['$location', '$rootScope', 'AuthUtils', //<== injected AuthUtils here 
    function ($location, $rootScope, AuthUtils) { //<== and here 

可用。

更改爲

$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute) //<--removed AuthUtils 

$rootScope.$on("$routeChangeSuccess", function (event, currentRoute, previousRoute, AuthUtils) 
+0

非常感謝你,但現在我已經一個錯誤「未捕獲的錯誤:[$注射器:unpr] HTTP://errors.angularjs。 org/1.5.0/$ injector/unpr?p0 = AuthUtilsProvider%20%3C-%20AuthUtils「 – Pablo

+1

@Pablo請仔細檢查。我認爲我的建議在回答中應該有效.. –

+0

謝謝,我按照上述我改變了命令導入js文件並且工作! – Pablo

相關問題