Retrieve localstorage value when value is change i

2020-02-29 23:37发布

I am using ionic 2 framework and I have tried using local storage to store a network status

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

There are 2 values that, "Strong" and "Weak" that can be assigned to status dynamically.


I am able to get my the initial value of my local storage "status" value on initialization of every page.

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

this will return me a "Strong" or "Weak", which is what I want, but is there any methods or event to dynamically (On "status" value change) call "toCheckStatus()" function?

Workflow Example (pseudo-code):

  1. On application start -> Check internet status (Background will keep checking and update local-storage value)
  2. Store status to local-storage
  3. Call a function to get the value (How to dynamically call this function when my value change, is there any method?)
  4. If Status is Weak -> Show Weak Icon
  5. If Status is Strong -> Show Strong icon

3条回答
欢心
2楼-- · 2020-03-01 00:04

This can be achieved with a BehaviorSubject along with the Storage module from Ionic.

Create a BehaviorSubject that you call .next() whenever you set a key in Storage and subscribe to that BehaviorSubject to get the updated value.

A code example of this:

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))
})

This will set a key in local storage which will be logged to the console, and asynchronously update that key after 5 seconds which then will be logged again to the console. You could refactor the setting of the key and updating the BehaviorSubject to a function.

查看更多
够拽才男人
3楼-- · 2020-03-01 00:08

How to dynamically call this function when my value change, is there any method?

A better solution will be using observables. You can use observables in your methods to emit events when a property is changed and then execute the code you need to execute.

This is a very simple example of using 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);
    }

And then in your page:

@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);
        });
    }
}

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

EDIT:

If you need to update something in the view, beacuse of something that has changed in the background, you will have to let Angular know of that change. One way to do it is by using Zones. You can check my answer here to know how to do it.

查看更多
Lonely孤独者°
4楼-- · 2020-03-01 00:11

Would it suffice to poll it? It might not be the cleanest way but it would get the data you need.

setInterval(function() {
  // Check localStorage every 2 seconds
}, 2000);
查看更多
登录 后发表回答