[英]how implement the observer pattern in IONIC 2
我想在IONIC 2中實現觀察者模式。
我有這項服務
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Events } from 'ionic-angular';
@Injectable()
export class ExampleService {
private _events: Events;
constructor(public http: Http, events: Events) {
this._events = events;
}
doStuff() {
this.raiseBeginDownloadData('data');
}
private raiseBeginDownloadData(hash: string){
this._events.publish('begin-download', hash);
}
}
這是我的控制器:
import { Component } from '@angular/core';
import { NavController, AlertController, Platform } from 'ionic-angular';
import { ExampleService } from '../../providers/example-service';
@Component({
selector: 'page-exaple',
templateUrl: 'example.html',
providers: [ExampleService]
})
export class MyPage {
constructor(public navCtrl: NavController, platform: Platform, public alertCtrl: AlertController, public eventSvc: ExampleService) {
}
}
我的問題是,在這種情況下如何實現觀察者模式?
我知道在我的服務中,我需要創建一種方法,以使控制器可以訂閱/取消訂閱該事件; 並且在控制器中,我需要創建一個notify方法,但是我不知道如何使用IONIC 2 / RxJs實現
非常感謝!
事件是一種發布-訂閱樣式的事件系統,用於在您的應用程序中發送和響應應用程序級事件。
因此,您可以在service
發出它並訂閱Component
。
import { Events } from 'ionic-angular';
constructor(public events: Events) {}
// first page (publish an event when a user is created)
function createUser(user) {
console.log('User created!')
events.publish('user:created', user, Date.now());
}
// second page (listen for the user created event)
events.subscribe('user:created', (user, time) => {
// user and time are the same arguments passed in `events.publish(user, time)`
console.log('Welcome', user, 'at', time);
});
就你而言。
export class MyPage {
constructor( public events: Events) { }
this.events.subscribe('begin-download', (user, time) => {
// user and time are the same arguments passed in `events.publish(user, time)`
console.log('Welcome', user, 'at', time);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.