2017-02-27 83 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) 

只要按下按钮。