Home > Net >  Angular HttpClient Service only returning responses with a statuscode of 200
Angular HttpClient Service only returning responses with a statuscode of 200

Time:10-12

I have a login component that calls an http client service which sends a request to my server to try to log in. If the credentials I enter are valid everything works, but whenever I enter wrong credentials my service apparently doesnt return anything at all.

This is the method that gets called when you click login:

  submit(){
    this.auth.tryLogin(this.form.getRawValue())
    .subscribe(res => {
      console.log(res);
      if(res.status == 200){
        this.router.navigate(['/'])
      }
      else{
        alert(res.status)
      }
    })
  }

and here is the code for the service

  tryLogin(data : any) : Observable<HttpResponse<any>> {
    return this.http.post<any>(environment.server   environment.routes.authRoutes.login, data, {
      withCredentials: true,
      observe: 'response'
    })
  }

Whenever I enter the correct credentials everythign works fine, the response gets logged to the console and I get redirected to my homepage:

But when I enter the wrong password/username it doesnt alert the status code and I have no idea why

Am I using the http client wrong, does it throw an exception when it recieves an error code in he respose? Is there something I am missing?

CodePudding user response:

Your implementation it's correct but it's going to work only for success case.

If you look at Observable sign, you can see that has some parameter:

const observer = {
  next: x => console.log('Observer got a next value: '   x),
  error: err => console.error('Observer got an error: '   err),
  complete: () => console.log('Observer got a complete notification'),
}; 

So in your case you have to:

submit(){
  this.auth.tryLogin(this.form.getRawValue())
  .subscribe(
    res => {
      console.log(res);
      if (res.status == 200) {
        this.router.navigate(['/'])
      }
      else {
        alert(res.status)
      }
    },
    err => alert(err)
  );
}

For more information you can follow Angular handling error

  • Related