kumara
kumara

Reputation: 937

how to display http error message angular 6

I am using the below methods to send data. I want to display an error response on my component. How can I console log error message in my component?

component.ts

signup(){ 
    return this.loginservice.signupUser(this.model).subscribe(data => {
        console.log(data.error);
    });
}

service ts

signupUser(signupuserModel: any = {}):Observable<any>{
    return this.http.post(`${this.signuouserurl}`,signupuserModel)
}

error message enter image description here

Upvotes: 2

Views: 11762

Answers (3)

Nithya Rajan
Nithya Rajan

Reputation: 4884

In RxJS, subscribe() method can have 3 functions

  1. next() if observable emits value.
  2. error() if there's an error thrown from the Observable
  3. complete() if the observable is completed.

What you need to do is to add an extra arrow function in your server call inside subscribe() method

public error: any; 

signup() { 
    return this.loginservice.signupUser(this.model).subscribe(success => {
        console.log(success);
    }, error => { // second parameter is to listen for error
        console.log(error);
        this.error = error;
    });
}

If you want to show the error in your component.html, you can use the interpolation {{ }}

component.html

<div class="error">{{ error }}</div>

Upvotes: 5

Kishan Oza
Kishan Oza

Reputation: 1735

you can choose any method to display an error.. on of the best way is seprate the success and error response with following code (for this your http call must thrown an exception if not then you have to chose the second option )

signup() { 
  return this.loginservice.signupUser(this.model).subscribe(success => {
    console.log(success);
  }, error => {
    console.log(error);
  });
}

or you can write conditional code like

    signup() { 
          return this.loginservice.signupUser(this.model).subscribe(success => {
            console.log(data);
    if(success.status == 406){ console.log("success")} 
else { console.log("Error ") }
          }
        }

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92467

try

signup() { 
  return this.loginservice.signupUser(this.model).subscribe(data => {
    console.log(data);
  }, err => {
    console.log(err);
  });
}

You can also use try-catch approach in following way

async signup() { 
  try {
    let data = await this.loginservice.signupUser(this.model).toPromise();
    console.log(data)
  } catch (e) {
    console.log(e);
  }
}

However not all http codes raise exception

Upvotes: 1

Related Questions