如何设置&进入angular2-localstorage?

时间:2016-08-18 05:50:52

标签: angular typescript local-storage angular-local-storage

repo开始,我已经成功配置了这个:

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

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

如何使用storageService设置或进入本地存储?即使在doc中我也找不到任何例子。

更新

经过一些测试,我已经设法让它通过WebStorage与Decorator合作:

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

然而,当我使用Chrome Dev查看我的本地存储时,我什么都没看到: enter image description here

在另一个组件中,

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

6 个答案:

答案 0 :(得分:6)

该服务仅导入应用程序,以便它可以运行初始化代码。

你应该使用它的方式是通过装饰器提到的其他答案。

请注意,这意味着您只需要将服务导入最根(app)组件,而不是所有使用装饰器的组件。

<强>更新

同时尝试使用instructions的第2步,使用bootstrap代替AppComponent

不幸的是,这个库正在寻找新的维护者。所以不确定它有多可靠。

答案 1 :(得分:4)

我知道它已经得到了回答,然而,这个答案旨在让答案更容易理解。

首先,您需要在主文件中执行此操作:

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

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

然后在组件中 SET 一个值,导入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
     }
}

要从其他组件中的本地存储重新获取,请执行以下操作:

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

检查您的chrome dev,您将保存localstorage: enter image description here

答案 2 :(得分:3)

查看GitHub-Page:https://github.com/marcj/angular2-localstorage

告诉我们这样使用它:

示例1

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

示例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 = {};
}

<强>更新

如果要在所有组件中使用它,则需要创建共享服务:

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

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

并像这样使用它(不要复制和粘贴!)

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

答案 3 :(得分:1)

来自文档:

  

使用LocalStorage装饰器

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

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

在这里:github

答案 4 :(得分:1)

您可以简单地执行以下操作

//在任何ts文件中设置

localStorage.setItem('variablekey',value);

//从任何其他ts文件中获取

localStorage.getItem("variablekey");

//如果你想要明确的价值那么

localStorage.removeItem("variablekey");

答案 5 :(得分:1)

我更愿意创建一个单独的Injectable服务

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

在你的组件中

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