Keep data in page after refresh

前端 未结 3 1991
醉话见心
醉话见心 2020-12-14 11:49

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

相关标签:
3条回答
  • 2020-12-14 12:07

    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()
      }
    
    }
    
    0 讨论(0)
  • 2020-12-14 12:07

    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.

    0 讨论(0)
  • 2020-12-14 12:10

    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 }
    
    0 讨论(0)
提交回复
热议问题