Vicheanak
Vicheanak

Reputation: 6684

How to Set & Get in angular2-localstorage?

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
     }
}

Upvotes: 10

Views: 35711

Answers (6)

Praveen M P
Praveen M P

Reputation: 11614

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');
    }
}

Upvotes: 1

ULLAS K
ULLAS K

Reputation: 901

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");

Upvotes: 1

Vicheanak
Vicheanak

Reputation: 6684

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

Upvotes: 4

Meligy
Meligy

Reputation: 36594

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.

Upvotes: 6

slaesh
slaesh

Reputation: 16917

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;
   }
}

Upvotes: 3

Daredzik
Daredzik

Reputation: 422

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

Upvotes: 1

Related Questions