【问题标题】:Angular observable - how to return true or false from subscription to observableAngular observable - 如何从订阅返回 true 或 false 到 observable
【发布时间】:2018-05-22 07:24:52
【问题描述】:

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

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

订阅this.modalRef.content.onClose 的result 正在工作。我可以成功登录true 或false。但是,当结果变为true 或false 时,我如何返回 true 或false 作为canDeactivate 的值?还是我没有抓住重点,我应该以不同的方式做事吗?

我的ConfirmationComponent 看起来像这样,它将onClose 定义为Observable&lt;boolean&gt;(特别是Subject&lt;boolean&gt;),所以我可以成功返回一个可观察的布尔值,但是如何让我的canDeactivate 返回@ 987654342@ 或 false 每当 openConfirmDialog 收到 true 或 false 的值?

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

【问题讨论】:

  • 您可以将onClose 返回的可观察对象映射到布尔可观察对象。 canDeactivate 的接口期望返回 boolean、observable 或 promise 类型
  • 谢谢大卫,我想我已经按照你的建议去做了——我已经发布了更多代码来更深入地展示正在发生的事情。希望我现在已经澄清了我在问什么?

标签: javascript angular observable ngx-bootstrap-modal


【解决方案1】:

感谢@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;
  }

【讨论】:

  • map 部分现在没有做任何事情。您可以删除该运算符。
猜你喜欢
  • 1970-01-01
  • 2017-02-17
  • 2019-03-09
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2017-03-26
  • 1970-01-01
  • 2018-09-01
相关资源
最近更新 更多