Search code examples
javascriptangularangular-ng-if

How to listen the 400 (Bad Request) with Angular *ngIf?


I won't paste any code, since this is a general question. I need to figure out how to listen if nothing returns. I can't get any objects, since nothing exists. I only receive on my GET request a message "400 (Bad Request)".(console).

How can I disable a button if there is a "400 (Bad Request)" (nothing exists)?

Is there a way to listen this on frontend?

Thanks


Solution

  • In Angular2 you would need to capture the error from the response.

    badRequest: boolean = false;
    
    this.appService.myHttpCall.subscribe(
       data =>  // do something with success,
       error => {
           if(error.status == 400){
              this.badRequest = true;
           }
       });
    

    And use the result in your template. If you really want to go the *ngIf route you would do this:

    <button *ngIf="badRequest" type="button" disabled>My Button</button>
    <button *ngIf="!badRequest" type="button">My Button</button>
    

    You would essentially have to code two buttons, both with *ngIf statements to get the result you want.

    If you want to use the [disabled] attribute you would do this:

    <button [disabled]="badRequest" type="button">My Button</button>
    

    However, I would not disabled a button if a BadRequest happens, because then how would the user resubmit the form after correctly filling it out? For example, if the user leaves a required field blank, the server returns a BadRequest and disables the button. Then the user cannot correct the missing field and re-submit the form.

    What I would do instead is to toggle the button's disabled attribute based on the validity of the form like this:

    <form (ngSubmit)="onSubmit()" #myForm="ngForm">
    
       ...inputs....    
    
        <button type="submit" class="btn btn-success" [disabled]="!myForm.valid">SUBMIT</button>
    
    </form>
    

    Hope this helps.