3

when I log in that time I am getting the response like below. I want to store the token and id in local storage and cookie. How could I call the data in angular6

{
    code: 200
    data:
    {
       alt_email: null
       balance: "100.00"
       current_institution_id: null
       designation: null
       id: 75
       token: "5c5d0d8cb6716"
    }
    status:true
}
TheParam
  • 10,113
  • 4
  • 40
  • 51
malar
  • 31
  • 5

3 Answers3

3

Try this simply -

let a = {
        code: 200,
        data: {
            alt_email: null,
            balance: "100.00",
            current_institution_id: null,
            designation: null,
            id: 75,
            token: "5c5d0d8cb6716",
        },
        status: true
    };

localStorage.setItem('token', a.data.token);
localStorage.setItem('id', a.data.id);

PS : In case of cookies data are always saved in name-value pair using the syntax like document.cookie.

For more details read here basic explanation here

Balaj Khan
  • 2,490
  • 2
  • 17
  • 30
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
1

If your response object is like this

 let res =    {
        code: 200
        data: {
        alt_email: null
        balance: "100.00"
        current_institution_id: null
        designation: null
        id: 75
        token: "5c5d0d8cb6716"
        }
        status:true
    }

then you can use

localStorage.setItem('id', res.data.id);
localStorage.setItem('token', res.data.token);

and you can retrieve anywhere using

localStorage.getItem('id');
localStorage.getItem('token');
dileepkumar jami
  • 2,185
  • 12
  • 15
0

I am assuming you get it as a response in the Observable that subscribes to login service, since you mentioned angular 6

this.someService.login().subscribe(res => {
  localStorage.setItem('token', res.data.token); // <-- add these lines
  localStorage.setItem('id', res.data.id);  // <-- 
});

For cookies, use a package or service as described here How to create cookies in Angular 6?

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25