首页 > 解决方案 > 如何在可观察管道序列中使用材质对话框

问题描述

对于我从 AngularJS 重写的应用程序,我有一系列操作:

1) I got to the server to get a message  
2) I display the returned message in a generic dialog, with a Yes and No button.  

3-Yes) I go to the server to do something, proceed to 4  
3-No) I terminate the sequence  

4) Notfiy the user that the operation is complete.

但是,我在将其转换为 Angular/ReactObservable系统时遇到了问题。我想做这样的事情:

// Actual arguments are immaterial in this case...
this.webDataService.get('/api/GetEndUserMessage', args)
  .pipe(
    map((message: string) => {
      const config = new MatDialogConfig();
      config.data = {
        'title': 'Important',
        'message': message
      };
      const dialog = this.matDialog.open(GenericDialogComponent, config);
      // If Yes/Ok is clicked, return 'Ok'
      // If No/Cancel is clicked, return 'Cancel'

      return dialog.afterClosed();
    }),
    // PROBLEM AREA! ----------------------------------------------
    filter((dialogResult: string) => {
      if (dialogResult === 'Ok')
        return this.webDataService.post('/api/DoSomethingAwesome');
    }),
    filter((dialogResult: string) => {
      if (dialogResult !== 'Ok')
        return 'Cancelled'
    })
    // PROBLEM AREA! ----------------------------------------------
  )
  .subscribe((result: any) => {
    if (result === 'Cancelled')
      return;

    // Let the user know that the sequence is over.  How doesn't matter.
  });

问题是,这显然不能编译。

我对 React 操作员系统的理解充其量是不稳定的,我不确定如何调用作为调用结果产生的 Observable MatDialogRef.afterClosed()

问题:
我可以通过什么方式按顺序使用MatDialogRef.afterClosed()调用的结果?Observable .pipe

标签: angularreactjsmodal-dialogangular-material

解决方案


switchMap当你需要改变 Observable 流时使用 a 。map()运算符只会使 observable 发出返回值。

this.webDataService.get('/api/GetEndUserMessage', args)
  .pipe(
    switchMap((message: string) => {
        //...
        const dialog = this.matDialog.open(GenericDialogComponent, config);
        return dialog.afterClosed();
    }),
    switchMap((dialogResult: string) => {
        return (dialogResult === 'Ok')
            ? this.webDataService.post('/api/DoSomethingAwesome')
            : of('Cancelled')
    })
).subscribe((result: any) => { ... });

https://www.learnrxjs.io/operators/transformation/switchmap.html


推荐阅读