2

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

1
  • What is the output of console.log(data.error); Commented Feb 26, 2019 at 4:24

3 Answers 3

5

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>
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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 ") }
          }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.