Including a JSON object in the $cookies array using AngularJS

When I check the console, my code is printing:

[Object, Object]

I am having trouble drilling down into the objects.

I have attempted to use JSON.Parse and JSON.stringify without any luck.

The service responsible for setting credentials:

setCredentials.js

'use strict';

// This service manages setting and getting cookies  

app.service('setCredentials', function($cookies) {

    // Function that takes a JSON object and stores it within a cookie
    this.storeInCookie = function(responseObject) {

        console.log(responseObject);

        // Set the cookie
        var cookieObj = {
            currentUser: {
                userType: responseObject.auth.userType,
                username: responseObject.auth.email,
                token: responseObject.auth.token
            }
        };


        console.log(cookieObj);
        // Set up header, in case we need auth token inside it for later 
        //$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; 
        // Store the data inside the cookie
        $cookies.put('globals', cookieObj);

        return true;

    };

    // Function to remove the cookie
    this.removeCookie = function() {



    };

    // Function to retrieve the cookie
    this.getCookie = function(cookieName) {

        // Get the cookie
        return $cookies.get(cookieName);

    };

});

Then, I access the cookie object in a controller:

navigationController.js

'use strict';

// Global variables for the app
// This controller handles post requests
// Declaring dependencies like $http, $location, custom service apiServiceWeb
app.controller('navigationController', function($scope, $rootScope, $http, $location, $cookies, setCredentials) {


  // Navigation menu

  // Get the content of the cookie
  var cookieValue = setCredentials.getCookie('globals');
  console.log($cookies.get('globals'));

});

Answer №1

Employ

$cookies.setObject('state', cookieObject)

as well as

$cookies.retrieveObject('state')

in place.

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

JavaScript shows undefined fields for results from Mongoose/MongoDB

Why is the item logging as an object with a parameter, but when trying to access that parameter it's undefined? My attempts so far: console.log(item) => { title: "foo", content: "bar" }, which is fine console.log(typeof item) => object consol ...

Sharing a single JSON object among Angular.JS controllers enhances collaboration and boosts efficiency

My current project involves coding a CRUD app using Angular.JS, and I could really use your expertise to move forward. Here is the situation: View 1 (index) retrieves JSONP data from a remote API and saves it. View 2 (master) displays filtered data on a ...

Unexpected Rotation Issue in Three.js Mesh (Global Rotation vs. Local Rotation)

While working with Three.js, I encountered an issue where the mesh I was trying to rotate using keyboard controls was not behaving as expected. Regardless of the axis I rotated around, the mesh did not rotate in the intended direction. Specifically, when ...

What is the best way to categorize a collection of objects within a string based on their distinct properties?

I am working with an array of hundreds of objects in JavaScript, each object follows this structure : object1 = { objectClass : Car, parentClass : Vehicle, name : BMW } object2 = { objectClass : Bicycle, parentClass : Vehicle, name : Giant } object3 = { ob ...

Turn off the scroll bar and mouse wheel functionality, while still allowing for scrolling

Is there a way to hide scrollbars on a website, prevent scrolling by mouse but still allow access to hidden areas using the jQuery scrollTo plugin function? (e.g. clicking on a button to scroll to a specific element) Thank you! ...

Struggling with configuring AngularJS?

I've been working on a simple setup, but I can't figure out why AngularJS isn't displaying the content within the curly brackets. It's got me completely baffled. If you'd like to check it out, here's the link to the plunker: ...

Use jQuery to change the background color when clicked

Below is the HTML code with UL and LI elements: <UL> <LI><span id='select1'>Text</span></LI> <LI><span id='select2'>Text</span></LI> <LI><span id='select3'>Tex ...

Error message: The function `useSession` is not defined within the Next.js

I'm currently working on a next.js project with next-auth, where I have successfully implemented the login functionality. However, I'm facing an issue when trying to use the session to fetch user data on a specific page. Whenever I attempt to use ...

Managing route rendering in nuxtjs: A guide

I came across Goldpage, a tool that allows for route rendering control. Render Control - With Goldpage, you have the flexibility to choose how and when your pages are rendered. For example, one page can be rendered to both HTML and the DOM (classic serv ...

Is it possible to push FormData using JQuery?

Can additional data be included in a FormData object used for file uploads, given that FormData does not support .push()? $("frm").submit(function (e) { e.preventDefault(); var data = new FormData($(this)[0]); }); ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Elevate sublevel vue component

I am facing an issue with a nested and reused vue component. I am attempting to use v-show to display a part of the component (icons) when its outer parent is hovered. In order to achieve this, I am passing the parent and child index as props. However, I ...

What is preventing me from passing arguments containing a hyphen to my node module through the command line?

Whenever I run my module using a script in package.json, I encounter an issue with passing command line arguments. Specifically, only the arguments that do not begin with a dash (-) are being transmitted successfully: npm run myscript -one two The argume ...

Authentication error occurs when attempting to login with Stormpath on the /me route using Safari, resulting from

Utilizing Stormpath for login on an Angular webapp with a Node/Express server has been successful on most modern browsers, except Safari. The issue seems to stem from access token cookies. It's unclear whether this is a bug or not. Upon logging in (u ...

Assigning the firebase downloadURL to a variable on the client side

I am working with an image upload feature in Firebase where I am receiving a downloadURL. How can I assign this value to my local variable image_url in Vue.js? //local variable data(){ return{ image_url : '', } } button trigger to ...

The res.redirect function is not functioning as anticipated

I recently added a middleware to my express app that redirects users to logout if the token is invalid. export async function validateAuthTokenMiddleware( req: Request, res: Response, next: NextFunction, ): Promise<NextFunction | void> { ...

uib-tabset directive loading based on a condition

I currently have a uib-tabset that looks like this: <uib-tabset active="activeJustified" justified="true"> <uib-tab index="0" heading="Address" > <by-adr></by-adr> </uib-tab> <uib-tab index="1" heading= ...

Exploring ways to loop through objects in a React application

I'm trying to figure out how to modify the code below to iterate through a custom object I have created. function itemContent(number) { return ( <div > <div className="item"> <div className="itemPic& ...

Issue with starting application in Angular because of $http request in primary module on Jasmine/Karma

Currently, I am manually bootstrapping my Angular application after receiving a response from an API call and setting a constant. Here is the code snippet: (function() { var myApp = angular.module('myApp'); // Bootstrap the app once we ...