Leverage cookies within a custom service in AngularJS

I attempted to implement angular cookies within a custom service, only to encounter the following error: Unknown provider: ngCookiesProvider <- ngCookies <- checkLoginService

My approach involves storing modules, 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*/
            }
        }
    }
})();

Answer №1

ngCookies is not just a dependency name, it is a module that needs to be injected into your app. Make sure to include ngCookies in your module dependencies and use $cookies to access the cookie object.

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

Don't forget to add $cookies as a dependency inside your checkLoginService $inject array.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The information does not display in the AngularJS-generated table

Struggling with AngularJS directives? Let's take a look at the code: <div ng-controller="Controller"> <table> <thead> ....... </thead> <tfoot> ....... </tfoot> <tbody> < ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

Ways to organize JSON information in Angular by date basis?

I am working on a project where I need to organize multiple JSON objects into an array based on their date data, with the date field serving as the key. ...

Changing the color of tabs using inline styles in material ui does not seem to work

I am brand new to using material ui and have been attempting to alter the colors of the selected tab. Currently, the color is a dark blue shade and I am aiming to change it to red. I tried applying inline styles, but unfortunately, there was no change. C ...

Tips on how to collapse all elements whenever one is being opened in a FAQ card using ReactJS

Clicking on a question reveals its text, and clicking on another collapses the previous one. The issue arises when trying to close an open question by clicking on it again - it doesn't work as intended due to a potential error in the If statement [im ...

Your request was denied by the Google Maps API server due to an invalid request. Please include the 'size' parameter in your request

I need to incorporate a static Google Map into my application built on node.js. Here is the code snippet: .panel.panel-primary .panel-heading h2.panel-title On the map .panel-body img.img-responsive.img-rounded(src="http://maps.googl ...

Using Typescript to mute audio elements within HTML documents

I have a scenario where I want to mute audio that automatically plays when the screen loads. In order to achieve this, I am attempting to add a button that can toggle the audio mute functionality using Typescript within an Angular4 application. The code sn ...

How to efficiently store data using ajax and php techniques

I'm currently working on sending data via ajax for the user_question and language input fields. Can anyone help me with the correct way to include this element in the ajax JavaScript code so that I can save the table element value in my database? Tha ...

Can one iterate over a JavaScript object using forEach() even if the keys are undefined?

During a code review, I came across the following code: var a = { ... }; // an object filled with key-value pairs for (var key in a) { if (!angular.isUndefined(key)) { do.stuff(); } } I am questioning whether key can ever be undefined or ...

Updating Time by Adding Minutes using ngFor Loop in Angular 4

I'm currently developing a scheduler that requires user input for start time and the time between two games. I am looking to display the time in a loop using ngFor, incrementing by minutes each time. How can I accomplish this within an Angular 4 HTML ...

How to use the var keyword in JavaScript to declare block-scoped variables

At this moment, my goal is to establish a block-scoped variable in JavaScript by utilizing the var keyword. I prefer not to utilize the let keyword due to compatibility issues with certain browsers in ecma6. Is there an optimal and universal method to ac ...

streamlining form updates in vue

The code snippet provided is functional but unnecessarily complicated and lengthy. I am seeking a more efficient approach to achieve the desired outcome. <h6><label for="number">Change Number</label></h6> ...

What is the best way to display a chosen item in a text input field?

https://i.stack.imgur.com/Qe5Ds.png Looking to create a similar design, but lacking the necessary expertise. What steps should I take or what is the specific term for this style? Seeking assistance in implementing this using jQuery, PHP, or JavaScript. A ...

Error encountered: The call stack size has been exceeded due to the combination of Node JS, MongoDB, and Mongoose

I am facing a RangeError issue while attempting to create a new object using a predefined schema and inserting it into my mongodb database. I need assistance in debugging this error and finding a solution for it. Any help would be appreciated, thanks. App ...

JavaScript Alert function doesn't wait for execution

I am facing an issue with my Signup page. After submitting the form, I use AJAX POST to send the data. The problem arises in the success function where an alert is triggered immediately without waiting for user input, leading to the execution of the next f ...

The HTML select element fails to drop down over the THREE.js scene

I'm currently working on enhancing the Three.js editor for a project. editor link One of the tasks I'm tackling is adding a select element on top of the viewport in the editor. Unfortunately, the dropdown functionality of the select element isn ...

Unable to locate the module name loaded using require() function

Within my React file, I am importing a Javascript file like this (I am using Typescript): let FloDialog = require('../public/js/flo-dialog.min'); Afterwards, I declare a property for the dialog class: dialog: FloDialog = null; It is important ...

Click on the child element while it is already being clicked by manually implementing the 'declick' function in Javascript

Hey there, I'm looking for suggestions on a better title for this issue. I couldn't come up with the right wording myself. Problem I currently have a Google Maps element with pointer events set to none, preventing it from being scrolled when ho ...

What are the steps to integrate <br> in a JavaScript code?

I have recently started learning about web development and I'm facing a challenge with this implementation. var obj = [[{ name: "John", age: 30, city: "New York"}, { name: "Ken", age: 35, city: "New Orleans"}]]; ...

Attempting to call a nested div class in JavaScript, but experiencing issues with the updated code when implemented in

Seeking assistance. In the process of creating a nested div inside body > div > div . You can find more information in this Stack Overflow thread. Check out my JSFiddle demo here: https://jsfiddle.net/41w8gjec/6/. You can also view the nested div ...