简体   繁体   English

如何在 Angular 中使用 RxJS finalize 来限制用户点击

[英]How to use RxJS finalize in Angular to limit user clicks

How to use rxjs finalized in angular to limit user from clicking the save button multiple times and sending request multiple times.如何使用 angular 中最终确定的 rxjs 来限制用户多次单击保存按钮和多次发送请求。

Assume this call is triggered by a button click on our form.假设这个调用是由点击我们表单的按钮触发的。 Many people still double-click on those buttons and we definitely want to prevent 2 calls being sent to our backend API.许多人仍然双击这些按钮,我们绝对希望防止 2 个调用被发送到我们的后端 API。

My code is below.我的代码如下。 Thanks for any help.谢谢你的帮助。

Code代码

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 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>

Instead of using finalize , it will be more straightforward to achieve the above logic by using the take() operator.与使用finalize不同,使用take()运算符来实现上述逻辑会更直接。 As stated on the RxJS documentation for take ,采取的 RxJS 文档中所述,

Emit provided number of values before completing.在完成之前发出提供的值数量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM