Krunal
Krunal

Reputation: 938

How to use data from the localstorage in angular 2

How to use data from the localstorage for the another component. Localstorage in service are:

localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success,res:res.data}));

I want to use id, username etc from the data in another component How it possible

Upvotes: 0

Views: 1119

Answers (4)

Krunal
Krunal

Reputation: 938

currentUser = JSON.parse(localStorage.getItem('currentUser')); userid= (this.currentUser.res.id);

Upvotes: 0

Sathish Kotha
Sathish Kotha

Reputation: 1111

Try like this.

    let currentUser = localStorage.getItem( 'currentUser' );
    this.token = JSON.parse( currentUser )['token'];
    this.username = JSON.parse( currentUser )['username'];

Upvotes: 0

Shailesh Ladumor
Shailesh Ladumor

Reputation: 7242

you can retrieve current user from storage like

create one function for get a current user in your user service and use it globally

getCurrentUser(): void {
return JSON.parse(localStorage.getItem('currentUser'));
}

Upvotes: 0

Riyaz K
Riyaz K

Reputation: 11

You can also add individual item to localstorage

To set item

    localStorage.setItem('username', 'ActualUserName');

To retrieve item

    let username= localStorage.getItem("username");

Upvotes: 0

Related Questions