How to store an object (of a class type) in browser's storage and retrieve it?

前端 未结 3 2346
生来不讨喜
生来不讨喜 2020-12-22 09:47

I want to have a page-reload proof class instances in my Angular 2 application.

In my component\'s .ts file I have classes:

export class AComponent i         


        
3条回答
  •  感情败类
    2020-12-22 10:14

    I would suggest with angular-2-local-storage node_module.

    Steps:

    1. Install npm install angular-2-local-storage
    2. Make sure that the package is added in the config.js(systemjs or webpack)
    3. Import the module and service as below

      import { LocalStorageModule,LocalStorageService} from 'angular-2-local-storage';
      
    4. Add the module to imports array and service to providers array as

       imports: [ BrowserModule,
         LocalStorageModule.withConfig({storageType: 'localStorage'}), ],
      
       providers:[LocalStorageService],
      
    5. Inject the Service as a dependency into component as below

      constructor(private localStorageService: LocalStorageService) {
              this.name = 'Angular-2-Local-Storage-Demo';
              this.localStorageService.add('a',this.user);
              console.log(this.localStorageService.get('a')); 
              this.valuFromLocalStorage= this.localStorageService.get('a')
      }
      

    LIVE DEMO

提交回复
热议问题