首页 > 代码库 > angular2 localStorage的使用
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 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 = {};}
angular2 localStorage的使用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。