美文网首页angularangular2.0Angular: Zero to Hero
Angular2 本地存储LocalStorage的使用

Angular2 本地存储LocalStorage的使用

作者: chunxueer | 来源:发表于2016-10-22 19:08 被阅读4059次

    在网站开发过程中,总有一些类似记录用户喜好的数据需要保存在客户端,比如记住用户名密码等。常规第一反应是使用cookie,但是cookie的使用有诸多的限制。于是HTML5规范中出来了LocalStorage,大小为5M。
    Angular2 关于LocalStorage的使用在github上有些例子,但大多都是基于2.0.* 或是beta版本的。我用的是最新版本Angular 2.1用不了,于是手动改了下。

    一、参考github项目:

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

    二、环境:

    Angular 2.1
    

    三、实现:

    添加文件app/core/common/local.storage.ts(文件位置根据自己喜好)
     import {Provider} from '@angular/core'; 
    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 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);
        }
    }
    // export const LOCAL_STORAGE_PROVIDERS:any[] = [
    //         Provider(LocalStorage, {useClass: LocalStorage})
    // ];
    

    四、使用:

    1、在文件app.module.ts 中引用
     
    import { LocalStorage } from './core/common/local.storage';
    ...
    @NgModule({
       ...
       providers: [LocalStorage,...],
    ...
    }) 
    
    2、在你的Component 中使用
     ...
    // 引用
    import { LocalStorage } from '../core/common/local.storage'
         // 注入
         constructor(
            private ls: LocalStorage,
         ...   
         ) 
     
        get(): void {
            // 读取LocalStorage
            this.cache = this.ls.getObject("logincache") ; 
        }
        set(): void { 
            // 写入LocalStorage
            this.ls.setObject("logincache",this.cache) ;
        }
    
    

    五、总结:

    才接触不太久,又没有Angular1的基础,使用Angular2比较吃力。网上资源太少,走的很艰难,只有多次修改、报错、再修改。
    以下是相关文件的全部代码,由于不是单独例子,多余其它功能代码请忽略,如你有更好的方法,欢迎指正!

    1、文件app/core/common/local.storage.ts
    import {Provider} from '@angular/core'; 
    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 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);
        }
    }
    // export const LOCAL_STORAGE_PROVIDERS:any[] = [
    //         Provider(LocalStorage, {useClass: LocalStorage})
    // ];
    
    
    2、文件app.module.ts
    
    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
    
    import './rxjs-extensions';
    
    import { LocalStorage } from './core/common/local.storage';
    
    import { AppComponent } from './app.component';
    import { IndexComponent } from './index/index.component';
    import { MainComponent } from './main/main.component';
    import { HelpComponent } from './help/help.component';
    
    import { Session } from './core/auth/session';
    
    import { AuthService } from './core/auth/auth.service';
    import { UserService } from './core/user/user.service';
    
    import { AppRoutingModule }     from './app-routing.module';
    
    @NgModule({
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule, 
      ],
      declarations: [
        AppComponent,IndexComponent,MainComponent,HelpComponent
      ],
      providers: [LocalStorage,AuthService,UserService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
    
    
    3、文件app/index/index.component.ts
    
    import { Component,OnInit,Input   } from '@angular/core';
    import { ActivatedRoute, Params } from '@angular/router';
    import { Location }               from '@angular/common';
    
    import { LocalStorage } from '../core/common/local.storage';
    
    import { AuthService } from '../core/auth/auth.service';
    import { Session }     from '../core/auth/session'; 
    import { User }        from '../core/user/user'; 
    
    
    import { LoginCache }        from './logincache'; 
    
    @Component({
    //  moduleId:module.id,
      selector: 'app-index',
      templateUrl: './index.component.html',
      styleUrls: ['./index.component.css']
    })
    export class IndexComponent implements OnInit  {
        @Input()
        cache:LoginCache;
        user:User;
    
        constructor(
            private ls: LocalStorage,
            private authService: AuthService, 
            private route: ActivatedRoute,
            private location: Location
        ) {}
    
        ngOnInit(): void {
                this.cache = this.ls.getObject("logincache") ; 
        }
        tologin(): void { 
            this.ls.setObject("logincache",this.cache) ;
            this.authService.login(this.cache.account,this.cache.password)
                            .then(user => this.user);
        }
    
     }
    
    

    我的其它博客将同步更新:
    CSDN
    简书

    github

    相关文章

      网友评论

      本文标题:Angular2 本地存储LocalStorage的使用

      本文链接:https://www.haomeiwen.com/subject/dyehuttx.html