2016-10-25 4 views
1

PublishSubscribe을 ionic-angular로 사용하려고합니다.이온 2 : 통화 이벤트 구독 및 수신 취소

subscribe.js

this.events.subscribe('done:eventA', (userEventData) => { 
    //Perform some operations 
    this.startEventB(); 
    this.events.unsubscribe('done:eventA'); <--- 
} 

this.events.subscribe('done:eventB', (userEventData) => { 
    //Perform some operations 
    this.startEventA(); 
} 

this.events.subscribe('done:eventA', (userEventData) => { 
    //Perform some operations 
    this.startEventC(); 
} 

startEventB(){ 
    this.events.publish('done:eventB', data); 
} 

startEventA(){ 
    this.events.publish('done:eventA', data); 
} 

처음 시간 이벤트 A가 내가 수행하고자 게시입니다 startEventB()
시간 이벤트 A는 내가 startEventC() 그래서 난에 노력 수행 할 게시입니다 unsubscribe 첫 부분부터.
하지만 unsubscribe 일 때 모든 구독이 취소되었습니다.

이벤트 구독 및 구독 취소에 대한 좋은 방법이 무엇인지 압니까?

답변

0

구독 취소에 두 번째 매개 변수를 전달하지 않으면 모든 구독자는 removed이됩니다. 주어진 가입자의 구독을 취소하려면 here과 같이 매우 동일한 대상을 구독하고 구독을 취소해야합니다.

내가 선호하는 또 다른 해결책은 RxJS 제목 유형 중 하나가있는 구성 요소간에 서비스를 공유하는 것입니다. 소스 클래스는 주제에서 다음에 수행하는 서비스 기능을 사용하여 공개 할 수 있으며 대상 클래스는 주제를 관찰 가능으로 가져 오는 스트림을 볼 수 있습니다.

import {Injectable} from '@angular/core'; 
import {Observable} from 'rxjs/Observable'; 
import {Subject} from 'rxjs/Subject'; 

import {Booking} from '../../common/model/booking'; 


@Injectable() 
export class BookingEventsService 
{ 
    private _newChannel: Subject<Booking> = new Subject<Booking>(); 


    constructor() 
    { 
    } 

    publishNew(booking: Booking) 
    { 
     this._newChannel.next(booking); 
    } 

    newChannel(): Observable<Booking> 
    { 
     return this._newChannel.asObservable(); 
    } 
} 

는 희망이 도움이 : 여기

당신은 서비스의이 종류의 예를 가지고있다. 감사합니다, Xavi