I have a question about whether it is possible to retrieve the value from a call to Subject.next(). Can you suggest any other approaches on how to receive a response in the given scenario?
My current situation involves a notify service that is used throughout the app. It displays a message box to the user, at minimum with an 'OK' button, and I need to be able to determine when the user clicks on this button:
import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class NotifyMessagesService {
private setMessageBoxData = new Subject<INotifyMessage>();
constructor() { }
getMessageBoxData(): Observable<INotifyMessage> {
return this.setMessageBoxData.asObservable();
}
public notifyMessageBox(message: string, header?: string)/*: Promise<any>*/ {
/*return new Promise(resolve => {*/
this.setMessageBoxData.next({ message: message, header: header });
/*resolve();*/ //The response from next() should go here
/* });*/
}
}
export interface INotifyMessage {
header?: string;
message: string;
}
I also have a component that subscribes to this service:
export class NotifyControllerComponent implements OnInit, OnDestroy {
@ViewChild('messageBox', null) messageBox: MessageBoxComponent;
subscription: Subscription;
constructor(private notifyService: NotifyMessagesService) {
this.subscription = this.notifyService
.getMessageBoxData()
.subscribe(message => {
if (message) {
this.messageBox.show(`${message.message}`
, `${message.header}`).then(() => {
//Here, I need to notify NotifyMessagesService that the user clicked on the message box
});
}
});
}
ngOnInit() { }
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
I would appreciate your advice on updating the code examples to achieve the following: Whenever I call the service, it should return after the user confirms the message box.
export class AnyComponent implements OnInit{
constructor(private notifyMessagesService: NotifyMessagesService){
}
showMessage(){
this.notifyMessagesService.notifyMessageBox('Hi','it works').then(res=>{
console.log('User reaction ' + res);
//Code continues here
});
}
}
-> Therefore, I believe the service method should be updated to return a Promise or Observable (as mentioned in the examples), but how can this be done?