javascriptangularjscookiesangular-cookies

AngularJs: use cookies inside custom service


I tried to use angular cookies in custom service, but got the error: Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService

I store module, controllers and services in separate files.

Controller:

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

Service:

    (function () {
    'use strict';

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

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

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

Solution

  • ngCookies is module not a dependency name, you should inject ngCookies in module dependency and use $cookies to get cookie object

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

    Also add $cookies missing dependency inside a checkLoginService $inject array.

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