Sivo 悉见

9、Angular2 本地存储LocalStorage的使用

匿名 · 更新于 2018/5/20

一、参考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);
    }

    }
 

作者:chunxueer
链接:https://www.jianshu.com/p/94afa6c4dbc1
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。