如何向/从ngx-bootstrap模式传递和接收数据?

Mar*_*rio 3 ngx-bootstrap angular ngx-bootstrap-modal

将数据传递给模态可以使用initialState完成,但是如何接收数据呢?例如,如果我想创建一个确认对话框?

Mar*_*rio 10

即使目前没有内置的方法,也可以通过绑定到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();
                }
            };
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }

}
Run Code Online (Sandbox Code Playgroud)

实施后,使用它非常简单:

confirm() {
    this.messageService
        .confirm(
            "Confirmation dialog box",
            "Are you sure you want to proceed?",
            ["Yes", "No"])
        .subscribe((answer) => {
            this.answers.push(answer);
        });
}
Run Code Online (Sandbox Code Playgroud)

您可以在此演示中获取完整代码并查看其运行情况.