我有这个 ionic 2 提供程序:
@Injectable()
export class SettingsProvider {
settingsData: SettingsDataModel = new SettingsDataModel(2, 2);
subscriber = null;
constructor(public http: Http, public storage: Storage) {
console.log('Hello SettingsProvider Provider');
}
load(): void {
this.storage.ready().then(() => {
// Or to get a key/value pair
this.storage.get('settingsData').then((val) => {
this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
});
})
}
save() {
this.storage.set('settingsData', this.settingsData);
this.subscriber(); // how to notify the subscriber (a differerent typescript class) there was a change the right way in ionic 2?
}
subscribe(callback) { // how to register a subscriber the right way in ionic 2?
this.subscriber = callback;
}
}
我已经实现了另一个类想要订阅并通过自定义代码(脆弱的代码(获取通知的能力,另一个类可以以正确的方式订阅它的实现是什么?
为了通知另一个代码块(如另一个服务(,您可以公开一个可观察属性,该属性表示一系列正在进行的事件。我们可以做到这一点 Subject
.
这是看起来的样子
import { Subject } from 'rxjs/subject';
// singleton can use true privacy.
const settingsEventSource = new Subject<SettingsDataModel>();
@Injectable() export default class SettingsProvider {
constructor(readonly http: Http, readonly storage: Storage) { }
get settings$() {
return settingsEventSource.asObservable(); // prevent others from sourcing events
}
settingsData = new SettingsDataModel(2, 2);
async load() {
await this.storage.ready();
try {
this.settingsData = await this.storage.get('settingsData');
settingsEventSource.next(this.settingsData);
}
catch (e) {
settingsEventSource.error('Error loading settings.');
}
}
async save() {
try {
await this.storage.set('settingsData', this.settingsData);
settingsEventSource.next(this.settingsData);
}
catch (e) {
settingsEventSource.error('Error saving settings.');
}
}
}
订阅者看起来像这样
import SettingsProvider from './settings-provider';
import SetttingsDataModel from './settings-data-model';
@Injectable() export default class SomeService {
constructor(settingsProvider: SettingsProvider) {
settingsProvider.subscribe(settings => {
this.settings = setttings;
});
}
}