2015-06-05 66 views
0

我想實現登錄模塊到AngularJS應用程序。我嘗試從(this)authenticationService調用UserService,但UserService未定義。我現在做錯了什麼,爲什麼UserService是未定義的?在AngularJS中注入服務到另一個服務

var authenticationService = angular.module('authenticationService', []); 

authenticationService.factory('authenticationSvc', ['$http', '$cookieStore', '$rootScope', '$timeout', 'UserService', 

function AuthenticationService($scope, $http, $cookieStore, $rootScope, $timeout, UserService) { 
    var service = {}; 

    service.Login = Login; 
    service.SetCredentials = SetCredentials; 
    service.ClearCredentials = ClearCredentials; 

    return service; 

function Login(username, password, callback) { 
     var response; 

     UserService.GetByUsername(username) //UserService is unidefined!!! 
       .then(function (user) { 
        if (user !== null && user.password === password) { 
         response = { success: true }; 
        } else { 
         response = { success: false, message: 'Username or password is incorrect' }; 
        } 
        callback(response); 
       }); 

    } 

回答

0

編輯:看看你的依賴注入:你應該有相同數量的依賴數組中的元素作爲函數中參數的數量。您在數組中注入$scope,而不是在參數中。您應該始終在兩者中注入每個依賴項,並按正確的順序注入:在這裏,Angular認爲$scope對應於您的$http參數,$http服務對應於您的$cookieStore參數,依此類推,直到UserService指向依賴項的第6個元素數組...這是未定義的。

嘗試

authenticationService.factory('authenticationSvc', ['$scope','$http', '$cookieStore', '$rootScope', '$timeout', 'UserService', 

    function AuthenticationService($scope, $http, $cookieStore, $rootScope, $timeout, UserService) { 
    ... 
    } 
]); 

相反。

另外,在該行

var authenticationService = angular.module('authenticationService', []); 

您創建一個沒有依賴一個新的模塊([])我的猜測是,UserService是另一個模塊中定義,未在本服務模塊中也沒有注入該應用的主要模塊,因此不可用。

備案:angular.module(name,array)創建一個新的模塊,它依賴於數組中傳遞的模塊。 angular.module(name)retreives以前創建的模塊。

我不認爲你需要一個單一的服務,雖然新的模塊。如果您在與UserService相同的模塊中定義驗證服務,則默認情況下它將可用。

編輯:另外,要小心你的命名模式:例如,給你的代碼,如果我想包括認證服務作爲服務的依賴,我必須包括authenticationSvc而不是authenticationService ...

+0

所以當我調用工廠並嘗試向UserService添加依賴關係時,這還不夠? – Sami

+0

如果他們在同一個模塊中就足夠了。但他們不是。相反,您必須將模塊作爲模塊依賴項注入,然後將服務本身作爲服務依賴項。 – Tiesselune

+0

@Sami Tiesselune是正確的,通過建議的設計,你應該保持在同一模塊中的所有服務 –

相關問題