問題描述
我正在使用 ionic 2 框架,并嘗試使用本地存儲來存儲網絡狀態
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);
});
}
這將返回一個強"或弱",這正是我想要的,但是否有任何方法或事件可以動態(在狀態"值更改時)調用toCheckStatus()"函數?
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):
- 在應用程序啟動時 -> 檢查互聯網狀態(后臺將不斷檢查并更新本地存儲值)
- 將狀態存儲到本地存儲
- 調用函數獲取值(我的值變化時如何動態調用這個函數,有什么方法嗎?)
- 如果狀態為弱 -> 顯示弱圖標
- 如果狀態為強 -> 顯示強圖標
推薦答案
我的值變化時如何動態調用這個函數,有什么方法嗎?
How to dynamically call this function when my value change, is there any method?
更好的解決方案是使用 observables
.您可以在方法中使用 observables
在屬性更改時發出事件,然后執行您需要執行的代碼.
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.
這是一個非常簡單的使用observables
的例子:
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);
}
然后在你的頁面中:
@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
.您可以查看我的答案這里 知道該怎么做.
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.
這篇關于當 Ionic 2 中的值發生變化時檢索本地存儲值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!