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

account.component.ts
will use
popup.service.ts
to show a popup
popup.component.ts
. And inside popup there is a button which needs to run a function inside
account.component.ts
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?'
};
this.popupService.showPopup(popup);
this.popupService.modalButton.subscribe(
success => {
// If OK button was pressed, continue
console.log(success);
}
);
}
}


Popup service

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

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


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 => {
value.next(true);

// 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
account.component.ts
?

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

popupSubject.next(true)

Whenever the button is pressed.

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