Saving an object in a cookie with AngularJS causes the outcome to display as [Object Object]

I'm attempting to store a group of user credentials in a cookie by passing in a user object to my service's SetCookie function:

this.SetCookie = function (user) {
    $cookies.user = user;
}

However, when I try to retrieve this cookie, instead of an object, all I get is a string that reads "[Object Object]".

While I can individually store each user credential in its own cookie, I find this method to be quite inefficient. Is there a simple solution to this issue? The top search result I came across regarding this problem involved JQuery and was not effective for me.

Answer №1

When working with Angular 1.4, I discovered a method for storing a JSON object in a cookie by following this approach:

var data = {
    user: {
        name: "JohnDoe",
        token: authToken
    }
};
$cookies.putObject('userData', data);

To retrieve the cookie's data, you can use the following code snippet:

var userDataCookie = $cookies.getObject('userData');

You can then access the values stored in the cookie like so:

var userName = userDataCookie.user.name;
var token = userDataCookie.user.token;

Answer №2

When you print an object directly, it will always display as [Object Object] because it contains a JSON object. However, if you use the alert method to print it, it will utilize the .toString() method to display it in the console.

To properly handle this, you should use JSON.stringify(user) to convert the JSON object to a string. When using the object, make sure to use JSON.parse(user) to convert it back to a JSON object.

Answer №3

Serialize the user object using JSON.stringify() before storing it in cookies.

Use JSON.parse($cookies.user) to convert the stored data back into an object.

Answer №4

To utilize cookies in Angular, it is necessary to inject the 'ngCookies' dependency in your controller or declare it within the angular.module('app', [ngCookies]). Avoid using $cookieStore as it has been deprecated.

var app = angular.module('myApp',['ngCookies']);
app.controller('cookiesController',['$scope','$cookies',function($scope,$cookies){
  //using put method you can add value using key value 
  $cookies.put('Kye','Admin');
  //access cookies value
  console.log($cookies.get('Key'));
  
  //You can also add an object in Cookies
  var data = {
            'name':'admin',
            'pass':'admin'
            }
  $cookies.putObject('data',data);
  //access object value
  console.log($cookies.getObject('data'));
  

}]);

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

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...

Searching for a way to access the child window URL within the parent window on a React.JS platform?

I am working on a ReactJS code and I need to open another URL in my child component. twitterPopup = () => { var currentChild = false; if (currentChild) child.close(); child = window.open( "http://10.10.1.1:9090/api/v1/twitter/login" ...

The React Component has been displayed on the screen a total of 5 times within the Ionic

While working on my app that includes a dashboard to display data, I noticed in Chrome's console that the render method is being called 5 times. This results in an annoying bouncing effect when the app page is re-rendered. How can I prevent the render ...

Tips for testing a directive with a template containing ng-include within an ng-repeat

I have created a directive where I am using ng-include inside an ng-repeat in the template: <div ng-repeat="page in wStepPages" id="step{{$index}}" data-ng-show="getCurrentStep() == $index" ng-include="page.page" class="slide-frame"> </div> ...

"Add a hover effect to fade the image and make it clickable for a

Is there a way to make the entire image a clickable link when it's hovered over, rather than just the text inside? I could use some assistance with this. Javascript: $('.thumbnail').hover(function() { $('.thumbnail img').stop ...

Sort object properties by value length in descending order using jq and Bash

Here is a JSON snippet that I have: { "root_path": "/www", "core_path": "/www/wp", "content_path": "/www/content", "vendor_path": "/www/vendor" } To start, I want to use jq to sort the values in descending order of length: /www/content / ...

What is the best way to make an array with values from a checkbox list?

I am working on a project that involves rendering a list of products categorized into different categories. Users can select these categories using checkboxes. Are you interested in learning how to create an array containing the selected values from the ch ...

Switch videos within the video tag as you scroll

I am trying to implement a video tag within a div element on my website. Here is the current code: <div class="phone" align="center"> <div class="phone-inner"> <video width="100%" height="100%" autoplay="" loop="" muted id="phonevideo ...

Trouble with uploading multiple files

I am attempting to upload multiple files along with form data using the Angular package found at https://github.com/danialfarid/angular-file-upload. Below is a snippet of my code: var files = ... // retrieve the files (this part is functioning correctly) ...

Creating a basic bar chart using NVD3 with X and Y axes in AngularJS

I'm currently utilizing the nvd3.js plugin within my angular-js application. I have a straightforward task of creating a bar chart, where bars represent months along the x-axis and revenue values on the y-axis. My goal is to accomplish this using the ...

The crossIcon on the MUI alert form won't let me close it

I am facing an issue with my snackBar and alert components from MUI. I am trying to close the alert using a function or by clicking on the crossIcon, but it's not working as expected. I have used code examples from MUI, but still can't figure out ...

Is there a way to automatically scroll to the last dynamically added div?

Within the chat.html file, I have included a div tag and implemented a script that dynamically adds rows to the div when a button is clicked. In another file named list.html, I have inserted an iframe tag with the src attribute pointing to chat.html. Howev ...

Managing and updating arrays in VueJS2: Conditionally push new items and update only if their properties have changed

I am currently facing an issue with my form where each time a user updates a value in an input field, a new array element is created and added to the form results. I'm looking for a way to update the properties of the existing array element without cr ...

Activate the Masterpage menu to emphasize its current state

I am currently utilizing the AdminLTE template on my website. One issue I have encountered is with the menu and its child menus. When redirecting to different pages using image buttons, the menu collapses back to its original state. While navigating throu ...

Error with constructor argument in NestJS validator

I've been attempting to implement the nest validator following the example in the 'pipes' document (https://docs.nestjs.com/pipes) under the "Object schema validation" section. I'm specifically working with the Joi example, which is fun ...

Guide to incorporating external CSS and JavaScript into an Angular 2 project with Express.js and Node.js

As a newcomer to Angular2 and NodeJs, I am eager to learn how to integrate external CSS and JS in an Angular2 and Nodejs express app. Specifically, I am looking to integrate a bootstrap admin theme into my Nodejs application. The screenshots below provide ...

Error encountered in Bootstrap 5: Popper__namespace.createPopper function is not defined

Currently using Django to host web pages. Focus is on enabling offline access by downloading all necessary resources to ensure webpage functionality, like Bootstrap 5. Attempting to utilize the dropdown menu feature in Bootstrap: Dropdowns depend o ...

Changes in a portion of the state for Vaadin's AbstractJavascriptComponent

I am currently working on implementing a JavaScript-based component for Vaadin that will be responsible for displaying and updating a large data set. To achieve this, I am extending AbstractJavaScriptComponent. My goal is to keep the JavaScript side as si ...

Despite the unconsumedBufferLength being 0, DataReader.loadAsync is still being completed

Working on UWP WinRT, I'm dealing with JSON stream consumption using the following code: async function connect() { let stream: MSStream; return new CancellableContext<void>( async (context) => { stream ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...