Keep data in page after refresh
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()
}
}
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 }
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.