【问题标题】:How to use RxJS finalize in Angular to limit user clicks如何在 Angular 中使用 RxJS finalize 来限制用户点击
【发布时间】:2020-05-07 02:48:50
【问题描述】:

如何使用 rxjs 以 Angular 完成,以限制用户多次单击保存按钮和多次发送请求。

假设这个调用是由点击我们表单的按钮触发的。许多人仍然双击这些按钮,我们肯定希望防止 2 个调用被发送到我们的后端 API。

我的代码如下。感谢您的帮助。

代码

save(): void {
    const create = this.requestFormService.createRequestData(this.form, this.respondents)
      .subscribe(
        (results: FeedbackRequest[]) => {
          this.hasBeenSubmitted = true;
        },
        (error) => {
          this.hasBeenSubmitted = false;
          this.handleInvalidFields(error, 'Failed to save the Feedback Request as draft. One or more fields contain invalid values. Input a valid value to proceed.');
          this.messageDialogService.show('Failed to save the Feedback Request as draft. One or more fields contain invalid values. Input a valid value to proceed.', true);
          create.unsubscribe();
        }
      );
  }

HTML

<button [disabled]="form.invalid || (!duplicateMode && !form.dirty) || (!editMode) || hasBeenSubmitted"
        mat-raised-button *ngIf="form" (click)="save()" type="submit">
        <ng-container>
          <span>SAVE</span>
        </ng-container>
      </button>

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    除了使用finalize,使用take() 运算符来实现上述逻辑会更直接。正如take 的 RxJS 文档中所述,

    在完成之前发出提供的值数。

    save(): void {
      const create = this.requestFormService.createRequestData(this.form, this.respondents)
        .pipe(
          take(1),
        ).subscribe((results: FeedbackRequest[]) => {
          this.hasBeenSubmitted = true;
        }, (error) => {
          this.hasBeenSubmitted = false;
          this.handleInvalidFields(error, 'Failed to save the Feedback Request as draft. One or more fields contain invalid values. Input a valid value to proceed.');
            this.messageDialogService.show('Failed to save the Feedback Request as draft. One or more fields contain invalid values. Input a valid value to proceed.', true);
          create.unsubscribe();
        }
      );
    }
    

    【讨论】:

    • 如何限制用户提交多个请求?
    • 因为这将确保用户在请求挂起时只会点击一次
    • 什么是 1 ?
    • 所以这意味着无论多少次用户 sumit 数据在请求完成之前都不会被创建?
    • 是的!这是正确的。它只接受 1 个发出的值,这是用户第一次点击它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-13
    • 2018-12-09
    相关资源
    最近更新 更多