Retrieve localstorage value when value is change in Ionic 2

后端 未结 3 878
北荒
北荒 2021-01-03 16:39

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\"         


        
3条回答
  •  悲哀的现实
    2021-01-03 16:56

    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.

提交回复
热议问题