在 Angular 中返回 observable 之前添加验证

add validations before returning observable in Angular

每次单击按钮时,如果模型形式无效,则会收到 return 通知消息,并且不会继续创建用户 (createUser)。

如果没有表单验证错误,它应该只在 returning this.accountService.create 上继续

功能是否干净且正确地实现了?是否存在导致此问题的主要问题?谢谢

我应该将 checkInputs 验证放在哪里,如果存在验证错误,则不应继续 this.accountService.create

#html代码

 <button #createUserBtn mat-flat-button color="primary" >Create
                    User</button>

#代码

@ViewChild('createUserBtn', { static: true, read: ElementRef })
  button: ElementRef;


  ngAfterViewInit(): void {
    fromEvent(this.button.nativeElement, 'click')
      .pipe(
        tap(x => x),
        exhaustMap(ev => {
          return this.createUser();
        })
      )
      .pipe(tap(x => x))
      .subscribe(this.handleResponse());
  }

  createUser(): Observable<any> {
    this.checkInputs();
    this.isInProgress = true;
    this.modelForm.markAllAsTouched();
    return this.accountService.create(this.modelForm.value).pipe(
        finalize(() => (this.isInProgress = false))
    );
  }

  handleResponse(): any {
    return {
      next: res => {
        this.notificationService.showSuccess('User has been created successfully.');
        this._router.navigate(['settings/user']);
      },
      error: err => {
        this.notificationService.showError('Something went wrong, Try again later.');
        this.isInProgress = false;
      },
      complete: () => this.isInProgress = false
    };
  }

  checkInputs() {
    if(this.userStatus == 'USER_ON_NO_ACCOUNT') {

      if(!this.modelForm.get('firstName').value) {
        this.notificationService.showError('First Name is required.');
        return;
      }

      if(!this.modelForm.get('lastName').value) {
        this.notificationService.showError('Last Name is required.');
        return;
      }

      if(!this.modelForm.get('companyName').value) {
        this.notificationService.showError('Company Name is required.');
        return;
      }
    }
    
    if(!this.modelForm.get('roleId').value) {
      this.notificationService.showError('Security Role is required.');
      return;
    }

    if(this.modelForm.get('roleId').value && this.modelForm.get('roleId').value !== 7 && !this.modelForm.get('isSso').value) {
      this.notificationService.showError('SSO is required.');
      return;
    }

    if(this.modelForm.get('roleId').value && this.modelForm.get('isSso').value && this.modelForm.get('isSso').value ==='Yes' && !this.modelForm.get('ssocredentials').value) {
      this.notificationService.showError('SSO Credential is required.');
      return;
    }

    if(this.modelForm.get('isSso').value ==='No') {
      this.modelForm.get('ssocredentials').setValue(null);
    }
  }

您可以在 this.accountService.create(this.modelForm.value) 之前添加 invalid 检查,但是您必须将 click 事件处理程序更改为如下所示:

  • 不需要以这种方式处理 click 事件,而是可以直接从模板添加事件处理程序:
<button mat-flat-button color="primary" (click)="createUser()">
  Create User
</button>
  • 不需要将 createUser 与其他 observables 链接起来,handleResponse 也是如此。相反,您可以在 createUser 方法中订阅 accountService.create 函数,并在其中处理 successfail,如下所示:
createUser(): void {
  this.checkInputs();
  this.isInProgress = true;
  this.modelForm.markAllAsTouched();

  // here you can check if the form is valid or not:
  if (this.modelForm.invalid) return;

  this.accountService.create(this.modelForm.value)
    .pipe(
      // take(1) is used to complete the observable after the result comes.
      take(1),
      catchError((err) => {
        this.notificationService.showError(
          'Something went wrong, Try again later.'
        );
        this.isInProgress = false;
        return EMPTY;
      }),
      finalize(() => (this.isInProgress = false))
    )
    .subscribe((res) => {
      this.notificationService.showSuccess(
        'User has been created successfully.'
      );
      this._router.navigate(['settings/user']);
    });
}
  • 您可以删除 ngAfterViewInit 块、handleResponse 方法和 button @ViewChild,因为上面的 createUser 会处理这些,并且 complete 从服务接收到结果后直接观察。