I want to send a POST call from my Ionic 2 app to an API. The API checks the data I send and then outputs either the statuscode 200 OK or 400 Bad Request. I want to execute a function when the statuscode is 200 and show an alert when the statuscode is 400. This is the code I have right now:
register(event) {
var firstname = this.registerForm.value.firstname;
var lastname = this.registerForm.value.lastname;
var email = this.registerForm.value.email;
var password = this.registerForm.value.password;
event.preventDefault();
this.backend.register(firstname, lastname, email, password)
.then(data => {
console.log("data after then: " + data);
this.data = data;
if (this.data == 200) {
this.toLogin();
} else {
console.log(this.data);
let alert = Alert.create({
title: 'Error',
subTitle: 'Error,
buttons: ['OK']
});
this.nav.present(alert);
};
});
}
register(firstname, lastname, email, password) {
return new Promise(resolve => {
var json = JSON.stringify({ firstname: firstname, lastname: lastname, email: email, password: password });
var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('someurl',
json, {
headers: headers
})
.map(res => res.json())
.subscribe(response => {
this.data = 200;
resolve(this.data);
}, error => {
this.data = 400;
resolve(this.data);
});
});
}
This always seems to show the alert, even when the network tab in the developer console shows a 200 OK, because data is set to 400 in the backend.register() function. I’m guessing this happens because the POST request doesn’t send data back, and thus the code in the error section is executed. Is there a way to implement what I’m looking for?