繁体   English   中英

如何在IONIC 2中实现观察者模式

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM