Search code examples
angularapirestauthenticationtoken

How to Get HttpErrorResponse Angular In Post Request to API


Sorry I'm New In Front End Developing

I already made a system login on angular but my system login doesn't return an error message if the token failed to get or got HttpErrorResponse

I want to show the error message as wrong password / username to user

This is the response if no username and password in my API

How to catch di response in my post method

api.service.ts

baseUrlAuth = 'http://localhost:8000/api/auth/token/login/'

auth.component.ts


interface TokenObj {
  auth_token: string;
}


 authForm = new FormGroup({
    username: new FormControl(''),
    password: new FormControl(''),
    rememberMe : new FormControl(''),
  });

  headers = new HttpHeaders({
    'Content-Type': 'application/json',
  });

  loginUser(authData) {
    let body = JSON.stringify(authData);
    return this.httpClient.post(this.ApiService.baseUrlAuth, body, {
      headers: this.headers
    },);
  }

  saveForm() {
    this.loginUser(this.authForm.value).subscribe(
      (result: TokenObj) => {
      if (this.authForm.value.rememberMe == true) {
        this.cookieService.set('userToken', result.auth_token)
      }
      sessionStorage.setItem('userSession', result.auth_token);
      window.location.href = '/home';}
      );
  }

auth.component.html

<div class="container">
    <div class="row">
        <div class="col col-8 col-sm-8 col-lg-6 mx-auto my-auto">
            <form [formGroup]="authForm" (ngSubmit)="saveForm()">

                <div class="form-group">
                    <label for="username">Username</label>
                    <input type="email" class="form-control" id="username" placeholder="Enter Username" required
                        formControlName="username">
                    <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone
                        else.</small>
                </div>

                <div class="form-group">
                    <label for="password">Password</label>
                    <input type="password" class="form-control" id="password" placeholder="Password"
                        formControlName="password" required>
                </div>

                <div class="form-check">
                    <input type="checkbox" formControlName="rememberMe" id="rememberMe" class="form-check-input">
                    <label for="rememberMe" class="form-check-label">Remember Me</label>
                </div>
                
                <div class="text-center">
                    <button type="submit" class="btn btn-primary" style="width: 250px;">Login</button>
                </div>

                <div class="text-center sign-up">
                    <p>Not a Member</p>
                    <a href="">Sign Up Now</a>
                </div>
            </form>
        </div>
    </div>
</div>


Solution

  • There is a error() method in the subscribe()

    app.component

    export class AppComponent {
      name = 'Angular ' + VERSION.major;
    
      constructor(private testService: TestService) {
        testService.fakeCall().subscribe(
          (data) => { // next() method block
            console.log("Log from next() method");
            console.log(data)
          },
          (error) => { // error() method block
            console.log("Log from error() method");
            console.log(error)
          }
        )
      }
    }
    

    test.service

    export class TestService {
    
      fakeCall() {
        return throwError("There is some error occurred...");
      }
    }
    

    You can check working example from this stackblitz

    I suggest you to refer HTTP interceptors in angular