簡體   English   中英

在AngularJS中將服務注入到另一個服務

[英]Injecting service to another service in AngularJS

我正在嘗試將登錄模塊實現為AngularJS應用。 我嘗試從(this)authenticationService調用UserService,但未定義UserService。 我現在在做什么錯,為什么未定義UserService?

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

    }

編輯:看看您的依賴項注入:您應該在依賴項數組中的元素數與函數中參數的數量相同。 您在數組中而不是在參數中注入$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) 檢索以前創建的模塊。

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

編輯:另外,請注意您的命名模式:例如,給定您的代碼,如果我想將身份驗證服務作為服務依賴項包含在內,則必須包含authenticationSvc而不是authenticationService ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM