Ngx_webstorage检索值为null

时间:2017-08-17 16:04:41

标签: angular

我正在使用带有ngx-webstorage的角度2。

首先我安装npm install --save ngx-webstorage

这是我的app.module.ts

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {Ng2Webstorage} from 'ngx-webstorage';

@NgModule({
    declarations: [...],
    imports: [
        BrowserModule,
        Ng2Webstorage,
        ],
    bootstrap: [...]
})
export class AppModule {
}

这是我的另一个组件。

 import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
    selector: 'foo',
    template: `
        <section>{{attribute}}</section>
        <section><button (click)="add()">Add</button></section>
        <section><button (click)="retrieveValue()">Retrieve</button></section>
    `,
})
export class FooComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

    add(){
      this.storage.store('boundValue',"Test");
    }

    retrieveValue() {
      this.attribute = this.storage.retrieve('boundValue');
      console.log(this.attribute);
    }

}

当我点击Add按钮时,我会存储boundvalue。然后点击Retrieve按钮检索'boundvalue'

这是工作。但我刷新了我的网页。boundvalue为空。

我每次都需要boundvalue。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

遇到类似问题时,是因为我无意间清理了存储空间。在项目中搜索“ this.storage.clear”,或查看已导入ngx-webstorage的每个组件,并查看是否在任何地方清除了存储。