What is the best way to load $cookies into an Angular service?

After defining an Angular service where I need to access a cookie, I noticed that the $cookieStore is deprecated and that it's recommended to use $cookies instead. This is how my service is set up:

'use strict';

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

lunchrServices.service('authService', ['$cookies', function ($cookies) {
    var user = $cookies.get('user') || null;

    this.login = function (userEmail) {
        user = userEmail;
        $cookies.put('user', userEmail)
    };
    this.logout = function () {
        user = null;
        $cookies.put('user', null);
    };
    this.currentUser = function(){
        return user;
    }

}]);

However, when I try to retrieve the user with $cookies.get('user'), I get an error saying

TypeError: undefined is not a function
. Strangely, if I switch every instance of $cookies to $cookieStore, it works without any issues:

'use strict';

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

lunchrServices.service('authService', ['$cookieStore', function ($cookieStore) {
    var user = $cookieStore.get('user') || null;

    this.login = function (userEmail) {
        user = userEmail;
        $cookieStore.put('user', userEmail)
    };
    this.logout = function () {
        user = null;
        $cookieStore.put('user', null);
    };
    this.currentUser = function(){
        return user;
    }

}]);

I would prefer to use $cookies over $cookieStore, but I'm puzzled as to why it's failing for one and not the other. Any insights on this issue would be greatly appreciated.

Answer №1

It seems likely that the issue is related to the excerpt from the documentation below:

BREAKING CHANGE: $cookies no longer provides access to direct properties representing browser cookie values. Instead, you should utilize the get/put/remove/etc. methods outlined in the updated documentation.

This implies that earlier versions of Angular may not have included these methods within $cookies.

Your current version could potentially be an older release without these functionalities.

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

Changes made to an Array are not reflected in AngularJS data-ng-repeat

I have created a custom directive that displays notes left by users for a product. The directive contains a div that shows all the notes stored in the $scope.MessageList. <mx-note-manager-two isModalPopup="true" is-show-date-range="{{IsSh ...

Transfer data via ajax to the controller

I need assistance with storing a file in my database using Tabulator without having a form already created. I am currently creating a simple input element like this: var editor = document.createElement("input");. After clicking the file, it trigg ...

Setting orientations for portrait and landscape views using Material UI breakpoints

Looking to implement portrait and landscape views for tablets using the styles object in Material UI. const tabletStyles = theme => ({ root: { padding: theme.spacing.unit, [theme.breakpoints.up('md')]: { backgroundColor: theme ...

Hello, I'm looking for assistance with this ReactJS code. Is there anyone who can help me

I am not receiving any output and also not encountering any errors, how can I resolve this issue? import React from 'react' function Array() { function myConcat() { const Villain = ["Harley Quinn", "Brainiac", "Deathstroke"]; cons ...

Jquery auto-suggest form validator

I have implemented a search dropdown menu using jQuery. Everything is working fine, and the 'not match' message displays properly when entering data that does not match any items. However, if I select an item from the dropdown and then modify it ...

How to iterate over an array and assign values to distinct labels using AngularJS

Challenge My goal is to present the user with information about their upcoming 4 events. I have used splice on an array to extract the first 4 objects. Now, I need to iterate through these objects and display the relevant data. Each label is unique and w ...

The Jquery click event is not triggering when clicked from a hyperlink reference

I have a specific HTML href in my code snippet: <a id="m_MC_hl6_8" class="no_loaderbox button_link inline_block " href="somelink" target="_self">link</a> Upon clicking this link, a waiting box is displayed on the page. However, I don't ...

What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scro ...

The npm error message states: "Unable to locate the 'readable-stream' module."

Recently, I installed node js on my Windows 10 machine with version v4.4.2. However, whenever I attempt to run npm install or check npm version, it throws the following error message. Any assistance on this matter would be highly appreciated. Error: Canno ...

A directive containing a template

I'm facing a unique challenge where I have to nest a template inside another template within my directive. The issue arises because AngularJS doesn't recognize ng-repeat code inside attributes. In an ideal scenario, here is how I envision my cod ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Using Node.js to parse XLSX files and generate JSON output

Recently, I came across an extremely well-documented node_module known as js-xlsx Curious: How can I convert xlsx to json format? This is the structure of the excel sheet: The desired json output should resemble the following: [ { "id": 1, "H ...

Information regarding gender vanishes upon refreshing the page

When the page is refreshed, the variable called jso disappears. Is there an alternative method for storing information that does not involve using a button? The goal is to have it work seamlessly when the page is reloaded without requiring any user action. ...

Limitations of GitHub's rate limiting are causing a delay in retrieving user commit history

I have developed a code snippet to retrieve the user's GitHub "streak" data, indicating how many consecutive days they have made commits. However, the current implementation uses recursion to send multiple requests to the GitHub API, causing rate-limi ...

Please indicate the number of lines for the href within the span element

I'm struggling with formatting a <span> tag, specifically the .lastMessageLink class that contains an <a> element with the .lastMessageText class. The content within .lastMessageText can vary from just a few characters to a lengthy paragra ...

async.series: flexible number of functions

Hello everyone, I'm currently working with Node.js (Express) and MongoDB (mongooseJS). My goal is to create a series of async functions that query the database in the right order. Here is my question: How do I go about creating a variable number of a ...

Transform the Vue.js component into a Webpack component

I found this code in a tutorial and now I need to make some modifications so it can be compiled with Webpack, including the template script and CSS files. <html> <head> <title>VueJs Instance</title> <s ...

issue with implementing the chart.js npm package

Just recently, I added chart.js to my project using npm. My goal is to utilize the package for creating graphs. npm install chart.js --save After the installation, I attempted to import the module with: import chart from 'Chartjs'; However, t ...

Retrieve the canvas coordinates for the images starting at lx and ending at rx on the x-axis, and

Currently, I am working on a project where I need to implement a drag and drop feature for an image within a PDF document. The goal is to retrieve the coordinates of the dragged image and use them later for document signing. The situation I am dealing wit ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...