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

时间:2016-12-19 20:32:15

标签: angular typescript ionic2 observable

我想在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) {

  }

}

我的问题是,在这种情况下如何实现观察者模式?

我知道在我的服务中我需要创建一个方法,使控制器能够订阅/取消订阅此事件;在控制器中,我需要创建一个通知方法,但我不知道如何使用IONIC 2 / RxJs

非常感谢!

1 个答案:

答案 0 :(得分:4)

  

Events是一个发布 - 订阅样式事件系统,用于发送和发送   响应您应用中的应用级事件。

因此,您可以在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);
  });
}