2017-02-27 21 views
0

私は2つの異なるコンポーネントをサービスを使って相互に作用させようとしています。 Observableでこれをやろうとしています。考え方はaccount.component.tspopup.service.tsを使用してポップアップpopup.component.tsを表示するということです。ポップアップの内側には、ポップアップの内側にあるaccount.component.tsの中で機能を実行する必要があるボタンがあります。RxJS Angular2コンポーネントObservablesとのやりとり

アカウントコンポーネント

export class AccountViewComponent implements OnInit { 
    constructor(popupService: PopupService) { } 
    openCancelPopup() { 
     let popup = { 
      'title': 'Popup title!', 
      'body': 'Are you really sure you wish to cancel your subscription?' 
     }; 
     this.popupService.showPopup(popup); 
     this.popupService.modalButton.subscribe(
      success => { 
       // If OK button was pressed, continue 
       console.log(success); 
      } 
     ); 
    } 
} 

ポップアップサービス

@Injectable() 
export class PopupService { 
    showPopupEmitter: EventEmitter<any> = new EventEmitter(); 
    modalButton: Observable<any>; 
    constructor() { } 

    showPopup(data: Object) { 
     this.showPopupEmitter.emit(data); 
    } 
} 

ポップアップコンポーネント

export class PopupComponent implements OnInit { 
    showPopup: boolean = false; 
    title: string; 
    body: string; 
    constructor(private popupService: PopupService) { } 

    close() { 
     this.showPopup = false; 
    } 

    openPopup(data) { 
     this.title = data.title; 
     this.body = data.body; 
     this.showPopup = true; 
     this.popupService.popupButton = new Observable(value => { 
      value.next(true); 

// I want to "resolve" here via button press 

     }); 
    } 

    ngOnInit() { 
     this.popupService.showPopupEmitter.subscribe(data => this.openPopup(data)); 
    } 
} 

現在の状態ポップアップが表示されていると、観察が瞬時に "解決" されていることです。私はどのようにボタンを押して解決するのですか?account.component.tsの中で私の機能を続けることができますか?

答えて

2

Subjectは、オブザーバとオブザーバブルの両方のオブジェクトです。ボタンが押されたときはいつでも

// You can chain as many Rx operators on this as you want 
let mySubscription = this.popupSubject.asObservable(); 

そして、それを介して値を渡すだけで

popupSubject.next(true) 

です:対象への登録

popupSubject = new Subject<bool>(); 

はほど簡単です。

関連する問題