Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  151] [ 6]  / answers: 1 / hits: 8476  / 4 Years ago, sun, july 26, 2020, 12:00:00

I am sending request with fetch api and make action according to the result is correct or it includes error.


my service code:


LoginUser(user: User) {
return fetch("http://localhost:8080/login", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(user)
});
}

and my then-catch code which calls the above one is:


async loginUser() {
let response = await this._service.LoginUser(this.user)
.then(response => {return response.json()})
.then(response => {this._router.navigate(['/mainpage'])})
.catch(error => {alert(error)});
}

Whether the response is coming with code 500 Internal Server Error still it is redirecting to /mainpage and does not recognise the error. How can I fix this problem ?


More From » angular

 Answers
7

If you are using async await you shouldnt have to chain on .thens like you are resolving a promise.


I adjusted your code and wrapped it in a try/catch, the try/catch error will handle an error from a non response however you will need to check your server response for errors itself


async loginUser() {

try {
let response = await this._service.LoginUser(this.user)

// Check your response for error this may not be response.error
if (response.error) {
// Handle error
alert(error)
} else {
// Navigate on success
this._router.navigate(['/mainpage'])
}
} catch (err) {
alert(err)
}
}

[#3066] Friday, July 24, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;