herrsiim herrsiim -4 years ago 166
TypeScript Question

RxJS Angular2 Component interaction with Observables

I'm trying to make 2 different components interact with each other using service. I'm trying to do this with Observable. The idea is that

will use
to show a popup
. And inside popup there is a button which needs to run a function inside
after being pressed inside popup.

Account component

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?'
success => {
// If OK button was pressed, continue

Popup service

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

showPopup(data: Object) {

Popup component

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 => {

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


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

Current state is that popup is shown and the observable is "resolved" instantly. How do I "resolve" it via button press so I could continue with my function inside

Answer Source

You could try using a Subject which is an object that is both an observer and an observable.

popupSubject = new Subject<bool>();

Subscribing to the subject is as easy as:

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

And passing a value through it is just


Whenever the button is pressed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download