mateuszs
mateuszs

Reputation: 165

Angular: Can you extract status of text responseType?

I have a project with server created with spring boot that returns ResponseEntity with String to post requests. I would like my angular application to react based on status of response.

this.httpClient.post(
    'http://localhost:8080/users',
    {
        "username": username,
        "email": email,
        "password": password
    },
    {
        observe: 'response'
    })
.subscribe(response => {
    if (response.status === 200) {
        alert('Hello!');
    }
 });

However with code above I get an error logged to console informing of:

"Http failure during parsing for http://localhost:8080/users"
(status is 200 as expected but alert does not work).

I know that I can change third parameter of post to

{responseType: 'text'}

and get rid of error with it however I don't know to get status code of such response.

Is there a way to do it?

Upvotes: 2

Views: 998

Answers (2)

Kirk Larkin
Kirk Larkin

Reputation: 93173

The first callback to subscribe is known as the next callback, which is called whenever the observable emits a value. If there's an error, the error callback is called, which can be provided as a second parameter to subscribe (there are other alternatives). The reason you're not seeing your alert fire when not using responseType: 'text' is because the callback function you've provided isn't called when there's an error.

As I've already suggested, one option would be to provide an error callback. Here's an example:

this.httpClient.post(
    'http://localhost:8080/users',
    { username, email, password },
    { observe: 'response' })
.subscribe(
    response => {
        // Only called for success.
        ...
    },
    errorResponse => {
        // Called when there's an error (e.g. parsing failure).
        if (errorResponse.status === 200) {
            alert('Hello (for real this time)!');
        }
    });

After re-reading the original question here, I think your real problem might just be that you're not combining responseType: 'text' and observe: 'response'. Here's what that would look like:

this.httpClient.post(
    'http://localhost:8080/users',
    { username, email, password },
    { observe: 'response', responseType: 'text' })
.subscribe(response => {
    if (response.status === 200) {
        alert('Hello!');
    }
});

Upvotes: 2

Manzurul
Manzurul

Reputation: 633

if (parseInt(response.status) === 200)

Since response.status is string and you cannot check with === operator since that check both type and value.

Upvotes: 0

Related Questions