I have a question, if is possible to return value from Subject.next() call. Or any other possible aproach how to get response in described scenario.
My situation: I have a notify service which is used everywhere in the app (it should show message box to user, min with button ok and I need to know that 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();*/ //HERE should go the response from next()
/* });*/
}
}
export interface INotifyMessage {
header?: string;
message: string;
}
And I have one component, which is subscribed 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 notify NotifyMessagesService back, that user click to the message box
});
}
});
}
ngOnInit() { }
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
Please advise how to update code examples to achive: from anywhere I call the service, it returns back after user confirm 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 continue
});
}
}
-> so I think that service method should be updated to return Promise, or Observable (as commented in examples), but how?