I have a Web API 2 register method as follows :-
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
and an angular Controller that posts to this api as follows :-
angular.module('monfusportsstoreApp')
.controller("registerCtrl", function($scope, UserService) {
var vm = this;
vm.register = register;
vm.Error = '';
function register() {
UserService.createUser(vm.user)
.then(function (response) {
console.log(response.data);
console.log(response.status);
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}
function parseErrors(response) {
var errors = [];
for (var key in response.ModelState) {
for (var i = 0; i < response.ModelState[key].length; i++) {
errors.push(response.ModelState[key][i]);
}
}
return errors;
}
})
and the UserService is as follows :-
angular.module("monfusportsstoreApp")
.factory("UserService", function($http, ENDPOINT_URI){
var url = ENDPOINT_URI + '/api/Account/';
var errorMessage = [];
return {
getAllUsers: function() {
return $http.get(url).then(handleSuccess, handleError('Error getting all users'));
},
createUser: function(user) {
return $http.post(url + "/Register", user)
.then(handleSuccess, handleError);
}
}
function handleSuccess(res) {
return res.data;
}
function handleError(res) {
return res.data;
}
});
Now I am managing to trap the response error correctly and displaying the message, however when the Register API is successful and sends the OK, the response is always empty, and as so this piece of code
if (response.success) {
console.log('Registration successful');
$location.path('/registerSuccess');
is never triggered.
How can I trap the status 200 OK so that I can redirect the user to the RegisterSuccess page?
Thanks for your help and time!
I have solved this question.
In the UserService, I needed to return
so that in the controller, I can capture the response status