当Ionic 2中的值发生变化时,检索localstorage值

时间:2016-07-04 02:29:33

标签: javascript angular typescript ionic2

我正在使用离子2框架,我尝试使用本地存储来存储网络状态

this.local = new Storage(LocalStorage);
this.local.set("status", this.status);

有两个值,“强”和“弱”可以动态分配给状态。

我可以在初始化每个页面时获取本地存储“status”值的初始值。

toCheckStatus();
function toCheckStatus()
{
    self.local = new Storage(LocalStorage);
    self.local.get('status').then((value) => 
    {
        console.log("status", value);
    });
}

这会给我一个“强”或“弱”,这就是我想要的,但有没有任何方法或事件动态(On“status”值改变)调用“toCheckStatus()”函数?

工作流程示例(伪代码):

  1. 在应用程序启动时 - >检查互联网状态(后台将继续检查并更新本地存储值)
  2. 将状态存储到local-storage
  3. 调用函数获取值(如果我的值发生变化时如何动态调用此函数,有没有方法?)
  4. 如果状态为弱 - >显示弱图标
  5. 如果状态很强 - >显示强大的图标

3 个答案:

答案 0 :(得分:3)

  

如果我的值发生变化时如何动态调用此函数,是否有任何方法?

更好的解决方案是使用observables。您可以在方法中使用observables在更改属性时发出事件,然后执行您需要执行的代码。

这是使用observables

的一个非常简单的示例
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class StorageService {

    private storageObserver: any;
    public storage: any;

    constructor(...) {
        this.storageObserver= null;

        this.storage= Observable.create(observer => {
            this.storageObserver= observer;
        });
    }

    public yourMethod(): void { 

        // This method changes the value of the storage
        // ...

        // Notify to the subscriptor that the value has changed
        this.storageObserver.next(newValue);
    }

然后在你的页面中:

@Component({
  templateUrl: 'build/pages/my-new-page/my-new-page.html',
  providers: [..., StorageService ]
})
export class MyNewPage {

    constructor(..., private storageService : StorageService ) {

        // Initialize all the things you need
        // ... 

        this.storageService.storage.subscribe((newValue) => {
                // This code will execute when the property has changed and also
                // you'll have access to the object with the information that
                // your service sent in the next() call.
                this.doWhatYouWant(newValue);
        });
    }
}

===========================================

编辑:

如果您需要更新视图中的某些内容,请注意背景中已更改的内容,您必须让Angular知道该更改。一种方法是使用Zones。您可以查看我的答案here以了解如何操作。

答案 1 :(得分:0)

这可以使用BehaviorSubject以及Ionic的存储模块来实现。

创建一个在存储中设置密钥时调用.next()的BehaviorSubject,并订阅该BehaviorSubject以获取更新的值。

这个代码示例:

let storageObserver = new BehaviorSubject(null)

this.storage.set("key", "data")
storageObserver.next(null)

setTimeout(() => {
  this.storage.set("key", "new data")
  storageObserver.next(null)
}, 5000)

storageObserver.subscribe(() => {
  this.storage.get("key")
    .then((val) => console.log("fetched", val))
})

这将在本地存储中设置一个键,该键将记录到控制台,并在5秒后异步更新该键,然后将再次记录到控制台。您可以重构键的设置并将BehaviorSubject更新为函数。

答案 2 :(得分:-1)

投票是否足够?它可能不是最干净的方式,但它可以获得您需要的数据。

sizeof