angular2 localStorage的使用

最近从ng1 转ng2 相信 使用ng1的同学都知道 ngStorage 这个插件吧, 存储 本地数据

下面介绍一下 ng2 使用 localStorage

参考

github

https://github.com/marcj/angular2-localstorage

使用方法

1 nodejs 下载 npm install --save angular2-localstorage

2 引入到AppModule

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

@NgModule({
    import: [WebStorageModule]
@Component({
    providers: [LocalStorageService]
})
export class AppModule {}

3 组件中使用

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

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

注意:在您正在使用的属性上始终定义默认值@LocalStorage

注意:localstorage键是默认的属性名称。定义@LocalStorage设置不同的第一个参数。

注意:请不要存储循环结构,因为此库在使用LocalStorage之前使用JSON.stringify进行编码。

注意:localstorage 后 再次刷新页面的时候,会先去 读取本地资源值,给属性赋值

举个栗子

@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;
}
@Component({
    selector: 'admin-menu',
    template: `
<div *ngFor="#menuItem of menuItems() | mapToIterable; #i = index">
    <h2 (click)="hiddenMenuItems[i] = !!!hiddenMenuItems[i]">
        {{i}}: {{category.label}}
    </h2>
    <div  [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 = {};
}