2017-02-27 86 views
0

我試圖讓2個不同的組件使用服務彼此進行交互。我試圖用Observable來做到這一點。這個想法是account.component.ts將使用popup.service.ts來顯示彈出popup.component.ts。彈出裏面有一個按鈕需要在account.component.ts裏面運行一個函數。RxJS Angular2與Observables的組件交互

Account組件

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這是一個既是觀察者又是觀察者的對象。

popupSubject = new Subject<bool>(); 

訂閱主題一樣簡單:

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

並傳遞一個值,通過它只是

popupSubject.next(true) 

只要按下按鈕。