javascript - Angular observable - 如何从订阅返回 true 或 false 到 observable

标签 javascript angular observable ngx-bootstrap-modal

我有一个函数 canDeactivate那应该返回 truefalse .这可以通过调用 openConfirmDialog() 的结果来确定。函数,它打开一个 ngx-bootstrap 模态“确认”对话框并等待用户响应(这可能导致 truefalse )。这是代码:

  canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
    // if there are no pending changes, just allow deactivation; else confirm first
    return component.canDeactivate() ?
      true :
      this.openConfirmDialog();
  }

  openConfirmDialog() {
    this.modalRef = this.modalService.show(ConfirmationComponent);
    return this.modalRef.content.onClose.subscribe(result => {
        console.log('results', result);
    })
  }

result从订阅 this.modalRef.content.onClose工作中。我可以成功登录 truefalse .当结果变为 truefalse不过,我如何返回 truefalse作为 canDeactivate 的值?还是我没捕获要点,我应该换一种方式做事吗?

我的 ConfirmationComponent看起来像这样,它定义了 onClose作为Observable<boolean> (特别是 Subject<boolean> ),所以我可以成功返回一个 bool 值可观察值,但我如何获得我的 canDeactivate返回 truefalse每当openConfirmDialog收到值 truefalse

@Component({
    templateUrl: './confirmation.component.html'
})
export class ConfirmationComponent {

    public onClose: Subject<boolean>;

    constructor(private _bsModalRef: BsModalRef) {

    }

    public ngOnInit(): void {
        this.onClose = new Subject();
    }

    public onConfirm(): void {
        this.onClose.next(true);
        this._bsModalRef.hide();
    }

    public onCancel(): void {
        this.onClose.next(false);
        this._bsModalRef.hide();
    }
}

最佳答案

感谢@David,我将对 onClose 的订阅更改为 map 而不是 subscribe 并且这有效:

  openConfirmDialog() {
    this.modalRef = this.modalService.show(ConfirmationComponent);
    // line below - change from 'subscribe' to 'map'
    return this.modalRef.content.onClose.map(result => {
        return result;
    })
  }

但是,正如@Ingo Burk 所指出的,我可以简单地使用:

  openConfirmDialog() {
    this.modalRef = this.modalService.show(ConfirmationComponent);
    return this.modalRef.content.onClose;
  }

关于javascript - Angular observable - 如何从订阅返回 true 或 false 到 observable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50442339/

相关文章:

javascript - 是否可以将向导控件侧边栏自定义为如下所示?

angular - typescript 中的运行时类型安全

angularjs - Angular2 $location.search() 等效(设置查询参数)

javascript - 降级 angular 2 指令或至少能够在 angular js 中使用它

triggers - Knockout.JS:根据可观察的变化触发

javascript - RxJS:将对象键映射到可观察值

javascript - 在复选框列表上启用 js ASP.NET Core

javascript - 如何使用jquery获取div的宽度?

javascript - Node.js 错误 "terminate called after throwing an instance of ' std::bad_alloc' what(): std::bad_alloc"

javascript - 可观察的订阅无法以非常短的间隔处理连续传入的数据