1

I have this method inside service code.

list.service.ts

public getList(id: string): Observable<ListData> {
  const url = this.config.getUrl + '/${id}'
  return this.http.get<ListData>(url);
}

and I'm trying to catch response code from this method and have user-friendly message on any error inside the component.

app.component.ts

public ngOnInit() {
  this.isWaiting = true;
  const id = 'testid'
  this.service.getList(id).pipe(
    finalize(() => this.isWaiting = false)
  ).subscribe(
    listData => //do something with success result,
    error => {   --------------------  error.status does not contain response code.
       if (error.status === '403')
        { console.log("You're not authorized") }
       else if (error.status === '500')
        { console.log("Something wrong!!") } 
       ....
       etc...

    }
  );
 }

But error.status is not returning anything here. Is there a proper way to catch http status code in this case?

1
  • Did my answer solve your problem ? Commented Jan 21, 2021 at 11:10

1 Answer 1

2

error.status is a number.

You're comparing a number with a string using the strict equality operator (===).
Obviously, this comparison will always fail as the types are different.

403 === '403'  // false
403 ==  '403'  // true

Either compare error.status with a number, or use the abstract equality operator (==).

if (error.status === 403)
// or
if (error.status == '403')
Sign up to request clarification or add additional context in comments.

2 Comments

This is the correct answer here in terms of the problem, but I would advise against changing to == operators. You should almost exclusively stick with ===. Another thing, if you for some reason NEED the status code you're comparing to to be a string, you can do String(error.status) === '403'.
He states that status code returns nothing. So this is more of a comment than an answer. I got the same problem with nothing being returned in the status code (0). Works in postman

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.