【发布时间】:2021-08-06 11:30:22
【问题描述】:
我有一个问题,是否可以从 Subject.next() 调用中返回值。或任何其他可能的方法如何在所描述的场景中获得响应。
我的情况: 我有一个在应用程序中随处使用的通知服务(它应该向用户显示消息框,最小按钮 ok,我需要知道用户点击了这个按钮):
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;
}
我有一个组件,它订阅了这项服务:
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();
}
}
请告知如何更新代码示例以实现: 从我调用服务的任何地方,它会在用户确认消息框后返回
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
});
}
}
-> 所以我认为应该更新服务方法以返回 Promise 或 Observable(如示例中所述),但是如何?
【问题讨论】:
-
我认为您可能以错误的方式处理此问题。添加一个回调函数作为可选参数,然后在用户单击按钮时执行该回调如何?
-
类似的东西我已经尝试过了,但效果不好。然后需要为这个回调订阅组件,要知道,用户点击,我需要以某种方式找到哪个代码在等待这个响应以及在哪里继续。
-
我不知道所有细节和用例,但最简单的方法是在您的服务中添加公共方法,该方法将发出另一个可观察的事件。您也可以用不同的类型将其包装为相同的 observable :) 然后您可以订阅不同的 observable 或相同的不同类型并按照您的意愿进行操作。
标签: angular typescript rxjs