【问题标题】:add validations before returning observable in Angular在 Angular 中返回 observable 之前添加验证
【发布时间】:2021-09-13 10:25:48
【问题描述】:

每次单击按钮时,如果模型表单无效,则返回通知消息并且不继续创建用户(createUser)。

如果没有表单验证错误,它应该只继续返回 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);
    }
  }

【问题讨论】:

    标签: javascript angular typescript validation rxjs


    【解决方案1】:

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

    • 无需以这种方式处理click 事件,您可以直接从模板中添加事件处理程序:
    <button mat-flat-button color="primary" (click)="createUser()">
      Create User
    </button>
    
    • 没有必要将createUser 与其他可观察对象链接起来,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 在接收到来自服务的结果后直接可观察到.

    【讨论】:

      猜你喜欢
      • 2020-10-25
      • 1970-01-01
      • 2021-06-20
      • 2018-08-07
      • 2021-05-01
      • 2019-01-22
      • 2021-04-25
      • 2019-03-15
      • 2017-06-27
      相关资源
      最近更新 更多