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

Using Node.js with the express framework for requiring and posting data

main.js: var mainApp = express(); require('./new_file.js')(mainApp); new_file.js: mainApp.post('/example', function(req, res) { console.log(true); }); Error message: mainApp is not defined. Looking for a solution to access exp ...

Using jQuery to toggle visibility based on scroll position

Recently, I received a web template equipped with a jQuery library called sticky, which essentially makes the navigation "stick" to the top of the page as you scroll. Now, my goal is to integrate a logo into the navigation once it reaches its final positio ...

Are you planning to print the JSON information?

I've been working on mastering JavaScript and decided to create a script that displays all public Facebook statuses related to a specific keyword. However, things aren't going as planned. You can find a sample URL where the JSON data is located h ...

**Finding the Index of a Table Row in Vue-Tables-2**

Recently, I came across some vue code that utilizes vue-tables-2. The table in question is quite simple and looks like this... <v-client-table :data="myRows" :columns="columns" :options="options"> <div slot=" ...

Is there a way for me to retrieve a variable from a $.getJSON function?

How can I access the StudentId variable outside of the $.getJSON() function? j.getJSON(url, data, function(result) { var studentId = result.Something; }); //need to use studentId here I suspect this issue is related to scopes and differs from how it ...

Evaluating the layout of a webpage with each new code update

I'm currently in search of a testing framework to evaluate the frontend and design aspects of my application. We are developing an Angular application and utilizing Protractor for end-to-end tests, but I am curious about how to test the visual design ...

Tips for maximizing the effectiveness of the .bind(this) method in Meteor js

Hey there, I've got a question for you. How do we go about using the bind method in Meteor? Take a look at this code snippet below. It feels like there's some repetition going on that bothers me. Thank you so much for sharing your thoughts! Bi ...

Is there a way to stop text from wrapping between words and punctuation marks using CSS or jQuery?

There is a paragraph containing some text. One issue I am facing is that punctuation at the end of a word may get wrapped to the next line, as shown here: This is the sentence, This is a new line Is there a way to fix this using CSS or jQuery? ...

Ensure that the link's color remains constant and remove any styling of text-decoration

Attempting to create a customized header. My goal is to change the color and remove text decoration in the navbar. Below is my code snippet: ReactJS: import React from 'react'; import './Header.css'; function Header() { return ( ...

What is the best way to access a post request value from one JavaScript file to another in a Node.js environment

Hey there, longtime listener, first-time caller. I'm diving into the world of node JS, Javascript, and express but I've hit a roadblock that's been giving me a headache for three days now. Hoping someone here can lend a hand. I have a &apos ...

What is the reason behind Node's error callback returning undefined first?

Whenever I try to run the error callback function, the code below returns undefined. I'm puzzled by why the JSON isn't being returned when the console log displays the entire query. Take a look at the function that is triggering the json to be l ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

Having difficulty injecting a factory into a controller in AngularJS

I'm currently restructuring my angular code by utilizing factories to prevent my controllers from becoming unmanageable. I plan on storing code in the factory that will be shared among various controllers. Despite my efforts, I'm facing difficul ...

If the condition is true, apply a class with ng-class when ng-click is triggered

I am facing a situation similar to toggling where I am adding the class col-xs-6 to divide the page into two views. Initially, when I click, I set a variable value as true and in ng-class, I check for a condition to append the col-xs-6 class. Below is the ...

Concealing UI elements within the primary stack during navigation to a nested stack in React navigation

Is there a way to hide the user interface in my main stack when I switch to the nested drawer stack? I am currently facing an issue where the header from my main stack appears above the header in my nested stack when I navigate to a screen using: navigat ...

Angular 9 Singleton Service Issue: Not Functioning as Expected

I have implemented a singleton service to manage shared data in my Angular application. The code for the service can be seen below: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataS ...

Why is the console log not working on a library that has been imported into a different React component?

Within my 'some-library' project, I added a console.log("message from some library") statement in the 'some-component.js' file. However, when I import 'some-component' from 'some-library' after running uglifyjs with ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

What is the process of setting up Express as an API web server and integrating a custom document renderer as middleware?

I have developed a code generator and I want to be able to execute it on the server. The generator utilizes pure native ECMA6 JavaScript to render HTML markup, but it is transpiled to ES5 before runtime using Babel and WebPack. I am looking to use this on ...

creating a loop to handle AJAX requests for JSON data

My JSON call successfully loads the data.root.offer[0].region data into a div with the class .region. Here is the code snippet: $.getJSON('json/data.json', function(data) { $('.region').html('<p>' + data.root.offer[0] ...