我正在使用 ionic 2 框架,并且尝试使用本地存储来存储网络状态
this.local = new Storage(LocalStorage);
this.local.set("status", this.status);
有两个值“强”和“弱”可以动态分配给状态。
我能够在每个页面初始化时获取本地存储“状态”值的初始值。
toCheckStatus();
function toCheckStatus()
{
self.local = new Storage(LocalStorage);
self.local.get('status').then((value) =>
{
console.log("status", value);
});
}
这将返回一个“强”或“弱”,这就是我想要的,但是是否有任何方法或事件可以动态(在“状态”值更改时)调用“toCheckStatus()”函数?
工作流程示例(伪代码):
- 应用程序启动时 -> 检查互联网状态(后台将不断检查并更新本地存储值)
- 将状态存储到本地存储
- 调用函数来获取值(如何在我的值改变时动态调用这个函数,有什么方法吗?)
- 如果状态为弱 -> 显示弱图标
- 如果状态为强 -> 显示强图标
如何在我的值改变时动态调用这个函数,有什么方法吗?
更好的解决方案将使用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);
});
}
}
=============================================
EDIT:
如果由于后台发生了某些变化而需要更新视图中的某些内容,则必须让 Angular 了解该更改。一种方法是使用Zones
。你可以看看我的回答here https://stackoverflow.com/questions/38174997/angular-2-ionic-2-detect-if-an-object-was-modified#answer-38180523知道如何去做。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)