答案 0 :(得分:9)
即使目前没有内置方法,也可以通过绑定onHide / onHidden事件来完成。
我们的想法是创建一个Observer,它将订阅onHidden事件并在从它接收数据时触发next()
。
我正在使用onHidden而不是onHide,因此所有CSS动画都会在返回结果之前完成。
我也在MessageService
中实现了它,以便更好地分离代码。
@Injectable()
export class MessageService {
bsModalRef: BsModalRef;
constructor(
private bsModalService: BsModalService,
) { }
confirm(title: string, message: string, options: string[]): Observable<string> {
const initialState = {
title: title,
message: message,
options: options,
};
this.bsModalRef = this.bsModalService.show(ConfirmDialogComponent, { initialState });
return new Observable<string>(this.getConfirmSubscriber());
}
private getConfirmSubscriber() {
return (observer) => {
const subscription = this.bsModalService.onHidden.subscribe((reason: string) => {
observer.next(this.bsModalRef.content.answer);
observer.complete();
});
return {
unsubscribe() {
subscription.unsubscribe();
}
};
}
}
}
ConfirmDialogComponent如下所示:
export class ConfirmDialogComponent {
title: string;
message: string;
options: string[];
answer: string = "";
constructor(
public bsModalRef: BsModalRef,
) { }
respond(answer: string) {
this.answer = answer;
this.bsModalRef.hide();
}
}
实施后,使用它非常简单:
confirm() {
this.messageService
.confirm(
"Confirmation dialog box",
"Are you sure you want to proceed?",
["Yes", "No"])
.subscribe((answer) => {
this.answers.push(answer);
});
}
您可以在此demo中获取完整代码并查看其运行情况。