2017-05-02 5 views
0

私はAngular2カスタムイベントが必要です。 subscribeイベントを呼び出すには?Angular2 Create map subscribe

BoardComponent.ts

onClickDelete() { 

    this.popupService.yesno("...?").subscribe(
     yes => { 
     console.log("E"); 
     }, 
     no => { 
     console.log("error") 
     } 
    ); 
} 

PopupService.ts

yesno(message: string):Observable<any> { 
     this.subject.next({ type: 'yesno', text: message }); 
     let obj:Observable<any> = new Observable(); 

     //How to..? ///////////////////////////// 
     return obj.map(() => { return {yes:'2'}; }); 
    } 

答えて

1

あなたは、この目的のためにReplaySubjectを使用することができます。

サービス:

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

@Injectable() 
export class EventSubscribeService { 

    private eventSubject: Subject<any> = new ReplaySubject(1); 

    constructor() { } 

// set observable of this subject 
    get $getEventSubject(): Observable<any> { 
    return this.eventSubject.asObservable(); 
    } 
// remove from observer 
    resetEventObserver(): void { 
    this.eventSubject = new ReplaySubject(1); 
    } 
// send event to observers 
    sendCustomEvent(param):void { 
    this.eventSubject.next(param); // you can send any parameter through here. 
    } 

} 

とコンポーネント:イベントを作成する方法

constructor(
     private serviceInstance: EventSubscribeService, 
) { 
//event will receive parameter. 
    this.serviceInstance.$getEventSubject.subscribe(event => { 
     // here you can do anything what you are going to do 
    }); 
    } 

onCustomEvent(param:any):void { 
    this.serviceInstance.sendCustomEvent(param); 
    } 
+0

ワウ!!だからありがとうU :) –

関連する問題