10

From this repo, I've successfully configured this:

import {Component} from "angular2/core";
import {LocalStorageService} from "angular2-localstorage/LocalStorageEmitter";

@Component({
    provider: [LocalStorageService]
})
export class AppRoot{
    constructor(private storageService: LocalStorageService){}
...
}

How can I use storageService to set or get in local storage? I can't find example anywhere even in the doc.

Updated

After some testing, I've managed it to get it working with Decorator through WebStorage:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage() public username:string = 'hello world';
     ngOnInit() {
         console.log('username', this.username);
         // it prints username hello world
     }
}

However, when I used Chrome Dev to see my localstorage, I see nothing there: enter image description here

And In another component,

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage() public username:string;
     ngOnInit() {
         console.log(this.username);
         // it prints null
     }
}
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Vicheanak
  • 6,444
  • 17
  • 64
  • 98

6 Answers6

6

The service is imported into the app only so that it can run initialisation code.

The way you are supposed to use this is via decorators as other answers mentioned.

Note that this means you only need to import the service into your root most (app) component only, not all the components that use the decorators.

Update

Also try using the first way in Step 2 of the instructions, using bootstrap instead of AppComponent.

Unfortunately this library is looking for a new maintainer. so not sure how reliable it is.

Meligy
  • 35,654
  • 11
  • 85
  • 109
  • Ok, I managed to use it with decorator by importing LocalStorage from WebStorage. @LocalStorage() public username:string = 'hello world'; However, I'm trying to call @LocalStorage() public username:string from another component, it gives me null value, while it actually supposed to give 'hello world' value. – Vicheanak Aug 18 '16 at 06:08
  • Maybe it's too early, is the call in constructor? See if it works inside `ngOnInit`, or `ngAfterViewInit`. – Meligy Aug 18 '16 at 06:11
  • Ok, I put it in ngOnInit, please check my question again that I've updated the issue. – Vicheanak Aug 18 '16 at 06:15
  • Have you got your bootstrap correct? step **2** in [here](https://github.com/marcj/angular2-localstorage#use). – Meligy Aug 18 '16 at 06:20
  • 1
    The last line in the code of that step in particular, `LocalStorageSubscriber(appPromise); ` – Meligy Aug 18 '16 at 06:23
  • 1
    Nice one bro! Works like charm! – Vicheanak Aug 18 '16 at 06:25
4

i know it's already been answered, however, this answer aims to make the answer easier to understand.

First you need to do this in your main file:

import {LocalStorageService, LocalStorageSubscriber} from 'angular2-localstorage/LocalStorageEmitter';
var appPromise = bootstrap(MyRootAppComponent, [ LocalStorageService ]);

// register LocalStorage, this registers our change-detection.
LocalStorageSubscriber(appPromise);

Then to SET a value, in your component, you import WebStorage:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class LoginComponent implements OnInit {
   @LocalStorage('username') public username:string; 
   //username as the parameter will help to use get function
     ngOnInit() {
         this.username = 'hello world';
         console.log('username', this.username);
         // it prints username hello world
     }
}

To GET a value back from the local storage in a different component, do this:

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

@Component({})
export class DashboardComponent implements OnInit {
   @LocalStorage('username') public username:string;
   //need to pass your own key parameter to get the value
     ngOnInit() {
         console.log(this.username);
         // it prints 'hello world'
     }
}

Check your chrome dev, you will localstorage is saved: enter image description here

Vicheanak
  • 6,444
  • 17
  • 64
  • 98
3

Taking a look at the GitHub-Page: https://github.com/marcj/angular2-localstorage

tells us to use it like this way:

Example1

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Component({
    selector: 'app-login',
    template: `
<form>
    <div>
        <input type="text" [(ngModel)]="username" placeholder="Username" />
        <input type="password" [(ngModel)]="password" placeholder="Password" />
    </div>

    <input type="checkbox" [(ngModel)]="rememberMe" /> Keep me logged in

    <button type="submit">Login</button>
</form>
    `
})
class AppLoginComponent {
    //here happens the magic. `username` is always restored from the localstorage when you reload the site
    @LocalStorage() public username:string = '';

    public password:string;

    //here happens the magic. `rememberMe` is always restored from the localstorage when you reload the site
    @LocalStorage() public rememberMe:boolean = false;
}

Example 2

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Component({
    selector: 'admin-menu',
    template: `
<div *ngFor="#menuItem of menuItems() | mapToIterable; #i = index">
    <h2 (click)="hiddenMenuItems[i] = !!!hiddenMenuItems[i]">
        {{i}}: {{category.label}}
    </h2>
    <div style="padding-left: 15px;" [hidden]="hiddenMenuItems[i]">
        <a href>Some sub menu item 1</a>
        <a href>Some sub menu item 2</a>
        <a href>Some sub menu item 3</a>
    </div>
</div>
    `
})
class AdminMenuComponent {
    public menuItems = [{title: 'Menu1'}, {title: 'Menu2'}, {title: 'Menu3'}];

    //here happens the magic. `hiddenMenuItems` is always restored from the localstorage when you reload the site
    @LocalStorage() public hiddenMenuItems:Array<boolean> = [];

    //here happens the magic. `profile` is always restored from the sessionStorage when you reload the site from the current tab/browser. This is perfect for more sensitive information that shouldn't stay once the user closes the browser.
    @SessionStorage() public profile:any = {};
}

UPDATE

If you want to use it in all of your components, you need to create a shared service:

import {LocalStorage} from "angular2-localstorage/WebStorage";

@Injectable()
export class MyStorageService {
   @LocalStorage() public username:string = '';
   constructor() {}
}

And use it like this (not copy&paste ready!)

export class Component1 {

   private username: string;

   constructor(private _storage: MyStorageService) {
      this.username = this._storage.username;
   }
}

export class Component2 {

   private username: string;

   constructor(private _storage: MyStorageService) {
      this.username = this._storage.username;
   }
}
slaesh
  • 16,659
  • 6
  • 50
  • 52
  • Ok, when I inject the @LocalStorage injector, it gives this error: Cannot find name 'LocalStorage'. – Vicheanak Aug 18 '16 at 05:56
  • Cause you didn't imported it. `import {LocalStorage} from "angular2-localstorage/WebStorage";` – slaesh Aug 18 '16 at 05:57
  • Ok, Import done, it's working, so is @LocalStorage() public username:string = ''; for setter or getter? How can I set the value to username? and how can I get the value from username? When I console.log(this.username), it gives me empty value. – Vicheanak Aug 18 '16 at 06:03
  • In a different component, when I call @LocalStorage() public username:string; it gives me null value, even in the other component i set to this: @LocalStorage() public username:string = 'hello world'; – Vicheanak Aug 18 '16 at 06:05
  • I assume its saved separated for every component (comp1.username, comp2.username, ...). If you want to have it available in all components you have to create a service. – slaesh Aug 18 '16 at 06:09
  • See my update. That angular2-localstorage class will save your 'username' for EACH component. Its NOT the SAME 'username' ! Each component can save it's own 'username'. – slaesh Aug 18 '16 at 06:18
  • But it doesn't save it in Chrome Dev, if I close the window and reopen again, will the local storage data be saved? – Vicheanak Aug 18 '16 at 06:20
  • I dont know that class/framework.. but as the name said, i would assume it! :) – slaesh Aug 18 '16 at 06:21
1

From documentation:

Use the LocalStorage decorator

import {LocalStorage, SessionStorage} from "angular2-localstorage/WebStorage";

class MySuperComponent {
    @LocalStorage() public lastSearchQuery:Object = {};
    @LocalStorage('differentLocalStorageKey') public lastSearchQuery:Object = {};
}

here you are: github

Daredzik
  • 422
  • 2
  • 9
  • 21
1

You can simple do as below

// set in any of your ts file

localStorage.setItem('variablekey',value);

// get from any other ts file

localStorage.getItem("variablekey");

// if you want clear value then

localStorage.removeItem("variablekey");
ULLAS K
  • 881
  • 2
  • 11
  • 24
1

I would prefer to create a separate Injectable service

import { Injectable } from '@angular/core';
@Injectable()
export class LocalStorageService {

    constructor() {
        //
    }

    public setData(key:string, data:any) {
        localStorage.setItem(key, JSON.stringify(data));
    }
    public getData(key:string) {
        return JSON.parse(localStorage.getItem(key));
    }

    public removeData(key:string) {
        localStorage.removeItem(key);
    }
}

And in your component

import { LocalStorageService } from './../../services/localStorageService';
@Component({
    selector: 'member-claims-modal',
    templateUrl: './view.html'
})

export class UserComponent {
constructor(private localStorageService:LocalStorageService) {
        super();
    }
    public SampleMethod() {
    let cloneData = {
            'claims': 'hello'
        };
    this.localStorageService.setData('claims', cloneData);
    let item=this.localStorageService.getData('claims');
    consoloe.log(item);
    this.localStorageService.removeData('claims');
    }
}
Praveen M P
  • 11,314
  • 7
  • 34
  • 41