AngularJs: 在自定义服务中使用 cookie

AngularJs: use cookies inside custom service

我尝试在自定义服务中使用 angular cookie,但出现错误: 未知提供者:ngCookiesProvider <- ngCookies <- checkLoginService

我将模块、控制器和服务存储在单独的文件中。

控制器:

    (function() {
    'use strict';

    angular
        .module('app')
        .controller('AuthController', AuthController);

    AuthController.$inject = ['$scope', '$http', '$location', 'checkLoginService'];

    function AuthController($scope, $http, $location, checkLoginService) {
        /* jshint validthis:true */
        var vm = this;
        vm.title = 'AuthController';

        $scope.login = function(user) {
            /*logic*/
        }

        $scope.checklogin = function () {
            if (checkLoginService.checkLogin()) {
                /*logic*/
            }
        }

        $scope.checklogin();
    }
})();

服务:

    (function () {
    'use strict';

    angular
        .module('app')
        .service('checkLoginService', ['ngCookies', checkLoginService]);

    checkLoginService.$inject = ['$http'];

    function checkLoginService($http, $cookies) {
        return {
            checkLogin: function () {
                /*logic*/
            }
        }
    }
})();

ngCookies是模块不是依赖名称,你应该在模块依赖中注入ngCookies并使用$cookies获取cookie对象

//somewhere in app.js
angular.module('app', ['otherModules', ..... , 'ngCookies'])

同时在 checkLoginService $inject 数组中添加 $cookies 缺少的依赖项。

angular.module('app')
.service('checkLoginService', ['$cookies', checkLoginService]);
checkLoginService.$inject = ['$http', '$cookies'];
function checkLoginService($http, $cookies) {
    return {
        checkLogin: function () {
            /*logic*/
        }
    }
}