在canDeactivate中返回Observable不起作用 [英] Return Observable in canDeactivate not working

查看:74
本文介绍了在canDeactivate中返回Observable不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个确认/取消模式对话框,当用户离开路线时会弹出.我通过对canDeactivate方法使用防护来做到这一点.但是,我希望canDeactivate等待它从模态中获取响应之后再返回任何内容.

I have a confirm/cancel modal dialog that pops up when a user leaves a route. I do this by using a guard with the canDeactivate method. However I want canDeactivate to wait until it gets a response from the modal before returning anything.

我试图通过返回一个可观察到的方法来做到这一点,但是它不起作用.

I have tried to do this by returning an observable but it is not working.

canDeactivate(): Observable<boolean> | boolean {
    if(this.isFormStarted()) {
        this.formService.showExitModal(true);
        return this.formService.getModalSelectionObservable();
    }
    else {
        return true;
    }
}

当我单击确认时,什么都没有发生,即使我在if块内执行console.log时也能观察到可观察的对象正常工作

Nothing is happening when I click confirm even though I can see that the observable is working fine when I do a console.log inside the if block

this.formService.getModalSelectionObservable().subscribe(
        value => console.log("dialog value: " + value)
    );

这是表单服务的外观.

private modalConfirmation = new Subject<boolean>();

public setModalSelectionObservable(confirmLeave: boolean) {
    this.modalConfirmation.next(confirmLeave);
}
public getModalSelectionObservable(): Observable<boolean> {
    return this.modalConfirmation.asObservable();
}

推荐答案

使用take(1)first()(不要忘记导入)

Use take(1) or first() (don't forget to import)

return this.formService.getModalSelectionObservable().first();

以确保可观察对象在第一个事件后关闭,否则路由器将等待直到从服务关闭.

to ensure the observable is closed after the first event, otherwise the router will wait until it is closed from the service.

这篇关于在canDeactivate中返回Observable不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆