R.H
R.H

Reputation: 318

How to check status in response from HTTP call

I am trying to navigate to next page if status code is 200 or response is true. But getting undefined in response.status. If I just log only response I get

{success: true, message: "login successful"}

This below code is getting undefined in console log. I am beginner to Angular and not using any service.

goToHome() {
    console.log(this.login);
    this.Http.post('http://localhost:3000/users/login', this.login).subscribe((response: Response) => {
      console.log(response.status);
      // if (resp.status === 200) {
      //   this.navCtrl.push(TabsPage);
      // } else {
      //   const toast = this.toastController.create({
      //     message: 'User not found please try again',
      //     duration: 2000
      //   });
      //   toast.present();
      // }
    })
  }

Upvotes: 2

Views: 464

Answers (2)

antonku
antonku

Reputation: 7665

You should use observe option ({observe: 'response'}) to get a full response that includes the response status code:

goToHome() {
    this.Http.post('http://localhost:3000/users/login', this.login, {observe: 'response'})
        .subscribe((response) => {
            console.log(response.status);
        })
}

Upvotes: 4

Patryk Uszyński
Patryk Uszyński

Reputation: 1119

You should add options to your request, and set observe: 'response' to read full response.

this.Http.post('http://localhost:3000/users/login', this.login, { observe: 'response' })
    .subscribe((response) => {
        console.log(response.status);
    })

More info in documentation: Reading the full response

Upvotes: 4

Related Questions