Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS: Storing an object in a cookie giving result of [Object Object]

I am trying to store a group of user credentials in a cookie when sending in this user object to my service -

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

However what I get when I try to retrieve this cookie I do not get an object but just a string that says "[Object Object]"

I can store all the user credentials individually in their own cookies, as I know I can make that work, but it seems pretty inefficient? Is there an easy fix for this? The top result I found for this problem was related to JQuery and did not work for me.

like image 270
user3407039 Avatar asked Jun 05 '15 08:06

user3407039


People also ask

Can I store object in cookie?

Store objects in the Cookies The cookies store information in the string format only. If users want to store any other types of data in the cookies, they need to convert it to the string using the stringify() method. In this section, we will convert the object to a string and store it in cookies.

How can you set get and clear cookies in AngularJS?

In AngularJs, we need to use angular-cookies. js to set, get and clear the cookies. We need to include $cookies in your controller and it have to Get, Set and Clear method to get, set and clear cookies respectively. Angular has inbuilt directives named as ngCookies.

What is object in AngularJS?

In AngularJS, $scope is the application object (the owner of application variables and functions). The controller creates two properties (variables) in the scope (firstName and lastName). The ng-model directives bind the input fields to the controller properties (firstName and lastName).


1 Answers

In Angular 1.4 I found that storing a JSON object by creating the cookie like this:

      var obj = {
        currentUser: {
          username: "testUN",
          authdata: authdata
        }
      };
      $cookies.putObject('cookieName', obj);

Allows you to get the cookie back like this:

var cookieWObject = $cookies.getObject('cookieName');

Then get to the values like this:

var username = cookieWObject.currentUser.username;
var authdata = cookieWObject.currentUser.authdata;
like image 130
sigmapi13 Avatar answered Oct 05 '22 19:10

sigmapi13