Reputation: 1683
I try to implement now a local Storage in Angular2 for the first time and get a bit confused.
So, I have First Component, where I register my user
export class FormComponent {
modus = ['first', 'second'];
model: User = new User('', '', '');
constructor(private _cookieService: CookieService) {}
}
Here is class, that I use in FormComponent
export class User {
constructor (
public email: string,
public name: string,
public modus: string
) {}
}
I bind it and everything in form works very good.
Now I want to store it in local storage (3 parameters of User
)
But how could I do this?
I leave this page with registration of user and go to other pages, like
export class Part1Component {
public email;
public name;
public modus;
constructor(private _location: Location) {}
myTestFunction(){
/* assign values here
this.email = ;
this.name = ;
this.modus = ;
*/
}
}
How could I get values from storage and assign them here?
Upvotes: 3
Views: 1005
Reputation: 2360
If you storing a user object in session storage by using JSON.stringify()
then you can do this
let user = JSON.parse(localStorage.getItem('user'));
this.email=user.email;
this.name=user.name;
Upvotes: 4
Reputation: 34711
Typescript provides localStorage
which you can use to set and get storage data.
Use the
localStorage.setItem(key, value);
method where you want to set the data.
localStorage.setItem('__user__email', user.email);
localStorage.setItem('__user__name', user.name);
localStorage.setItem('__user__modus', user.modus);
.. and
localStorage.getItem(key);
where you want to get the data.
myTestFunction() {
// assign values here
this.email = localStorage.getItem('__user__email');
this.name = localStorage.getItem('__user__name');
this.modus = localStorage.getItem('__user__modus');
}
You can have a look at this utility class and use that I created in one of my projects:
Upvotes: 5
Reputation: 11696
You should use localStorage.setItem()
to save your data and localStorage.getItem()
to get your saved data from localStorage. Please read this localStorage Documentation for more details.
Here is a simple example for using localStorage.
Save data to localStorage:
localStorage.setItem('userKey', JSON.stringify(this.model));
Beware that you can save only strings to localStorage.
Get saved data from localStorage for your Example:
let savedUser: User = JSON.parse(localStorage.getItem('userKey'));
If you want to clear or remove saved data you can use following code:
localStorage.removeItem('userKey');
or
localStorage.clear();
You can request your data from every point to localStorage in your application.
Upvotes: 1
Reputation: 3
use html5 localStorage like this
localStorage.setItem("key",value) set a item and then you can get it even you close the borwser.
localStorage.getItem("key");
and it save as string
Upvotes: 0