2016-12-19 3 views
0

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で作成するのかわかりません

ありがとうございます!

答えて

4

イベントは、アプリ全体のアプリケーションレベルのイベントに応答して を送信するためのパブリッシュ/サブスクライブスタイルのイベントシステムです。

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); 
    }); 
} 
関連する問題