【问题标题】:How to create a filter on observables that will need the user to confirm it?如何在需要用户确认的可观察对象上创建过滤器?
【发布时间】:2019-01-06 11:17:48
【问题描述】:

我正在使用材料单选按钮使用户能够更改服务器上的某些数据,但我希望他在对话框中确认,如果用户错误单击单选按钮,数据不会影响服务器数据当然我不想使用浏览器确认警报? 我的想法是使用 rxjs 的过滤器运算符?

this.validForWalletPresenter.change.pipe(
  filter(()=> confirm('are you sure you want to edit?')),
  switchMap(x => {
    return <--- calling the server here --->
  })
).subscribe(x => {
  <--- handle server response here --->
});

编辑

confirm 的问题是我无法自定义它,它就像一个警报,而且非常丑陋,我的问题是我如何创建一些行为类似于确认但显示我自己的模式而不是警报的东西?

【问题讨论】:

  • 您为什么不想使用浏览器确认警报?
  • 因为它很丑,而且不是我想的那种棱角分明的方式。
  • 为什么不显示一个像ng-smart-modal 这样好看的madal 作为确认窗口?
  • 你能解释/评论一下你的代码吗?如果您可以使您的示例通用并仅提供相关信息,那将是最好的。

标签: angular rxjs reactive-programming


【解决方案1】:

这是您打算执行的操作:

你可以在这里找到一个演示 https://stackblitz.com/edit/angular-ti7ecy

const changeResult$ = this.options.change.pipe(
  tap(change => {
    // open the dialog here
  }),
  switchMap(change => {
    return dialogResult$.pipe( // observable of dialog result
      take(1),                 // take 1 to complete the dialog stream
      map(confirmed => {
        if (!confirmed) {
          // set the value to previous value
        }
        return {confirmed, value} // combine values of two streams
      }),
      tap(result => {
        // close the dialog and set the state of radio to result of above
        this.options.value = result.value;
      })
    )
  }),
  filter(result => result.confirmed), // filter out not confirmed
  map(result => result.value)         // map to value
);

changeResult$
  .pipe(switchMap(result => {
    // send the request
  }))
  .subscribe(resp =>{
    // handle response
  });

【讨论】:

    【解决方案2】:

    您可以在filter 中运行confirm

    const { fromEvent } = rxjs; // = require("rxjs")
    const { filter } = rxjs.operators; // = require("rxjs/operators")
    
    const button = document.getElementById('button');
    const click$ = fromEvent(button, 'click');
    
    const confirmed$ = click$.pipe(
      filter(() => window.confirm("Are you sure?"))
    );
    
    confirmed$.subscribe(e => console.log("Click confirmed!"));
    <script src="https://unpkg.com/rxjs@6.3.3/bundles/rxjs.umd.min.js"></script>
    <button id="button">Click on me</button>

    但请记住,confirm 会阻塞 javascript 线程,并且在 UX 方面不好。见MDN Notes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-23
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多