【问题标题】:How to subscribe to angularMaterial Dialog afterClosed?如何在关闭后订阅 angularMaterial Dialog?
【发布时间】:2017-02-20 11:14:12
【问题描述】:

关于关闭对话框。 https://material.angular.io/components/component/dialog afterClosed 不可以吗?

在官方主要文档中:

错误

Property 'then' does not exist on type '() => Observable<any>'. [default] Checking finished with 1 errors

我试过订阅,但也没有用。

【问题讨论】:

    标签: angular angular-material


    【解决方案1】:

    【讨论】:

    • :-) 它之所以有效是因为它这样做了this._afterClosed.next(this._result); this._afterClosed.complete();
    • 这应该是公认的答案。 @VladimirB 的回答不正确。
    • 如果他们改变 afterClosed 的行为以在模态关闭时不完成。这有多大可能。无论如何,有一个安全网并取消订阅您的代码不是更好吗?
    【解决方案2】:

    基于示例部分他们的documentation

    let dialogRef = this.dialog.open(DialogResultExampleDialog);
    
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
    });
    

    但如果需要,您始终可以将结果转换为承诺

    dialogRef.afterClosed().toPromise()
    

    别忘了添加toPromise支持

    import "rxjs/add/operator/toPromise";
    

    【讨论】:

    • 我们查看的是相同的文档吗?在我的版本中(我截屏)我看到.then.subscribe 来自哪个文档?
    • 是的,打开考试标签。在这里您可以找到工作示例
    • 试试这个:let subscription = dialogRef.afterClosed().subscribe(); subscription.unsubscribe();
    • 应该立即调用取消订阅还是 onDestroy()?
    • 在这种情况下,Observable 是一个“有限的 observable”(.next() 被调用,.complete() 紧随其后),所以我们不需要取消订阅,根据netbasal.com/when-to-unsubscribe-in-angular-d61c6b21bad3
    【解决方案3】:

    https://material.angular.io/components/component/dialog

    afterClosed 方法返回一个 Observable,因此它不像 Promise 对象那样可操作。

    为避免在 Observable 上使用 toPromise 方法,您可以使用 take(1) 在之后自动退订第一个事件:

    dialogRef.afterClosed().take(1).subscribe(result => {
      console.log(`Dialog result: ${result}`); // Pizza!
    });
    

    【讨论】:

    • 不需要取消订阅。虽然在内部是 Subject<R>,但它会立即完成 this._afterClosed.next(this._result); this._afterClosed.complete();,因此 take(1) 没有任何用处 - 但总的来说,这是一种很好的做法,如果您不确定,也不会造成伤害!
    • 根据您的 UI/UX 设计,对话框可能会在底层组件已切换时保持活动状态。组件1消失后无需退订,组件中创建的对话框可以在组件现在就位时继续执行处理。您可能想要也可能不想要这样的工作流程。如果您不想要,请在组件 1 的 ngOnDestroy 中取消订阅。
    【解决方案4】:

    您也可以使用 first() RxJs 运算符代替 take(1)。就我个人而言,它看起来更好(尽管它们的效果相同)。

    dialogRef.afterClosed().first().subscribe(result => {
    console.log(`Dialog result: ${result}`);
    });
    

    【讨论】:

    • first() 和 take(1) 不一样
    • 你说得对,我的朋友。最好使用 take(1)。竖起大拇指
    猜你喜欢
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 2020-06-01
    • 2017-01-17
    • 2021-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多