Reputation:
I have 2 pages in my angular project.One of them is main page.The other one is popup page. I enter data to input tags in my popup page,then when i click the add button data is added to main page.It is working nicely.I hold data an array in my main page.But if i refresh the page (main page) data does not seem anymore.Do you have any idea?
I made a some researches and have learned localstorage and cookies.But i can send data from a page to other page.What i want to do is keep data in page.How can i handle it?
What i understand is we use localstorage to send data another page.Am i right?
Upvotes: 18
Views: 58574
Reputation: 3740
This can be done with a localStorage.
An example:
localStorage.removeItem('Array');
localStorage.setItem('Array', JSON.stringify(this.array));
The above is how you save it to get it back you do this in the ngOnInit:
this.array = JSON.parse(localStorage.getItem('Array'));
localStorage.removeItem('Array'); // to clear it again.
EDIT
Import:
import { OnInit } from '@angular/core';
Implement it on your component(class):
export class YourClass implements OnInit
And after constructor:
ngOnInit() { // your code here }
Upvotes: 18
Reputation: 1751
I would create a simple service which can help you to manage the localStorage data. Something simple like:
import { Injectable } from '@angular/core';
@Injectable()
export class SharingService {
private storageName: string = "Settings";
constructor() { }
setSettings(data: any) {
localStorage.setItem(this.storageName, JSON.stringify(data));
}
getUserSettings() {
let data = localStorage.getItem(this.storageName);
return JSON.parse(data);
}
clearUserSettings() {
localStorage.removeItem(this.storageName);
}
cleanAll() {
localStorage.clear()
}
}
Upvotes: 22
Reputation: 676
As you said, window.localStorage
is a way to go. You store data in localStorage
and it will be preserved even after closing session. In angular, you can make a service to streamline access specific data from storage.
To reload data from localStorage
as you enter page, you can use ngOnInit
lifecycle hook to load data from storage and fill your view.
Upvotes: 2