轨迹

为未来留点回忆的迹象

Angular中LocalStorage的使用

一、参考项目

https://github.com/NilsHolger/angular2todoes
https://github.com/rrgarciach/angular2-local-storage

二、环境

三、具体操作

1、新建一个ts文件(我的文件路径 ../src/app/utils/dataStore.ts

export class LocalStorage {

  public localStorage:any;

  constructor() {
    if (!localStorage) {
      throw new Error('Current browser does not support Local Storage');
    }
    this.localStorage = localStorage;
  }

  public set(key:string, value:string):void {
    this.localStorage[key] = value;
  }

  public get(key:string):string {
    return this.localStorage[key] || false;
  }

  public setArr(key:string, value:Array<any>):void{
    this.localStorage[key] = value;
  }

  public setObject(key:string, value:any):void {
    this.localStorage[key] = JSON.stringify(value);
  }

  public getObject(key:string):any {
    return JSON.parse(this.localStorage[key] || '{}');
  }

  public remove(key:string):any {
    this.localStorage.removeItem(key);
  }
  public removeAll():any{

    this.localStorage.clear();
  }



}



2、在app.module.ts中引用

import {LocalStorage} from "../../utils/dataStore";
...
@NgModule({
   ...
   providers: [LocalStorage,...],
...
}) 

3、在组件(component)中使用

import {LocalStorage} from "../../utils/dataStore";
     // 注入
     constructor(
        private LSData: LocalStorage,
     ...   
     ) 
 
setMessage(name,psd){//举例
    const json = {userName:name,pass:psd};
    this.LSData.setObject('userMsg',json);//存储到LocalStorage
}
getMessage(name,psd){//举例
    const userMsg=this.LSData.getObject('userMsg');//从LocalStorage获取userMsg
}

    }
做过好久了想起来了更新哈如果有什么新的见解请多多指教吐舌头吐舌头吐舌头
阅读更多
文章标签: Angular LocalStorage -
个人分类: angular
想对作者说点什么? 我来说一句

cookie使用localStorage使用

2015年03月18日 181KB 下载

没有更多推荐了,返回首页

不良信息举报

Angular中LocalStorage的使用

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭