Search code examples
angularngrxngrx-store

Unable to submit the the form the second time angular + ngrx


I have form in angular, I am using dispatching the action to submit it. it submits the first time. I have backend validation which checks for some requirements of the field and responds back to front end with error. The second time I would like to submit the form after entering correct input. But it doesnt execute the effect which submits / call API to submit the form values.

HTML component is:

<form [formGroup]="narForm" (ngSubmit)="onSubmit()">

  <mat-form-field>
          <mat-label for="narId" class="teal-txt">ID</mat-label>
          <input type="tel" minlength="8" maxlength="9" matInput formControlName="Id" required>

        </mat-form-field>

          <br>
          <mat-form-field>
            <mat-label for="email" class="teal-txt">Email Address</mat-label>
            <input type="email" matInput formControlName="email" required
              email>

          </mat-form-field>

  <div class="mt-5">
     <button type="submit" type="submit">Submit Form</button>
  </div>

component.ts is (submit form action)

onSubmit() {
    console.log('SUBMITTING THE FORM')
    this.isFormValid = true

    if (this.narForm.invalid) {
      console.log('Missing details in form submission')
      return
    }

    console.log('Submitting the form', viewQuoteFormFields)
    this.store.dispatch(new CartActions.Start())
  }

=======================================

*.EFFECT.ts is

@Effect() start$ = this.actions$
    .pipe(ofType(CartActionTypes.START))
    .pipe(withLatestFrom(this.store$))
    .pipe(map(([, state]) => {
      return {
        address: getCoveredAddress(state),
        ...selectQuoteForm(state),
        isNAR: 'true',
        isRE: 'true'
      } as ViewQuoteRequest
    }))
    .pipe(switchMap((request: ViewQuoteRequest) => this.api.cart(request)))
    .pipe(catchError(err => {
      console.log('Get Cart failed---+++--> ', err)
      this.oversizedPropetyError = err.error.error.errorKey
      if (this.oversizedPropetyError === 'over5kErrorMessage'
      || this.oversizedPropetyError === 'over10kErrorMessage') {
        this.store$.dispatch(new CartActions.ErrorHandler(this.oversizedPropetyError))
      } else {
        this.store$.dispatch(new CartActions.ErrorHandler(err))
      }
      return ([])
    }))
    .pipe(map(
      (result) =>
       new CartActions.GetCart(JSON.parse(result).cart),
       tap(result => console.log('++++++++++++++======+++++++++', result)
      )))

Solution

  • You have to catch the errors on the "api stream"

    .

    pipe(
      switchMap((request: ViewQuoteRequest) => 
        this.api.cart(request)
         .pipe(catchError(...))
      )
    )
    

    More info: Safe HTTP calls with RxJS - by StrongBrew