Not getting response when register is successful - javascript

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
function handleSuccess(res) {
return res.status;
}
so that in the controller, I can capture the response status
function register() {
UserService.createUser(vm.user)
.then(function (response) {
if (response == 200) {
console.log('Registration successful');
$location.path('/registerSuccess');
} else {
errorMessages = parseErrors(response);
for (var i = 0; i < errorMessages.length; i++) {
vm.Error += errorMessages[i];
}
}
});
}

Related

login authentication issue in angularjs

I have created login page and for accessing data I have used JSON File. when I click on the login() btn , userdata should match with the server data. But I am getting error and I am not able to send the $http response to the client side from server. If the rows with that name and password matches it return true, if not return false. then the client should parse this response.
But I don't know how What I am doing wrong?
Any help / advice would be greatly appreciated.
AngualJS:
/* server-side */
app.factory('auth', function ($http, session) {
var authService = {};
authService.login = function (username, password) {
var response;
$http.post('http://localhost:3000/loginfo')
.then(
function successCallback(response) {
var user = response.data;
console.log(user);
if (user.username == username && user.password == password) {
var signinfo = response.data;
console.log(response.data);
} else {
console.log('Error');
}
})
};
authService.isAuthenticated = function () {
return {
isAuthenticated: false,
user: null
}
};
return authService;
});
/* client-side */
app.controller('credientials', function ($scope, $http, auth) {
$scope.userCred = {
username: '',
password: ''
};
/*-----Form Submition-----*/
$scope.log = function (userCred) {
auth.isAuthenticated = true;
auth.login(userCred.username, userCred.password, function (response) {
if (response.success) {
console.log('success');
} else {
console.log('Error');
}
})
};
});

Angular controller structure

I'm a beginner with AngularsJs and I've got a question about the controller structure.
This is my employeeController.js
(function()
{
angular.module('employeeApp').controller('employeeController', employeeController);
function employeeController(employeeFactory,$routeParams,departmentFactory,schoolFactory,mentorFactory,constants,$location,$scope) {
var vm = this;
vm.employee = null;
vm.employees = null;
vm.profilePicture = null;
vm.mentors = null;
vm.schools = null;
vm.departments = null;
vm.roleId = constants.roleid;
vm.internEducators = null;
vm.overviewMentors = function() {
mentorFactory.overview(constants.companyid).then(function(response)
{
vm.mentors = response;
});
}
vm.create = function()
{
employeeFactory.create(vm.employee,vm.profilePicture).success(function(response,status)
{
if(status == 200)
{
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewInternEducators = function() {
employeeFactory.overviewInternEducators(constants.companyid).then(function(response)
{
vm.internEducators = response;
});
}
vm.overviewSchools = function() {
schoolFactory.overview(constants.companyid).then(function(response)
{
if(angular.isDefined(response[0].SchoolId))
{
vm.schools = response;
}
else
{
console.log('leeg!');
}
});
}
vm.overviewDepartments = function() {
console.log('test');
departmentFactory.overview(constants.companyid).then(function(response)
{
vm.departments = response;
});
}
vm.show = function() {
vm.isAdmin = employeeFactory.isAdmin();
employeeFactory.show($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.showDeleted = function() {
employeeFactory.showDeleted($routeParams.id).then(function(response)
{
vm.employee = response;
});
}
vm.update = function()
{
employeeFactory.update(vm.employee, vm.profilePicture).success(function(response, status)
{
if(status == 200)
{
vm.show(); // Zodat de nieuwe afbeelding wordt weergegeven
$.toaster({ message: 'De werknemer is geupdated' });
}
}).error(function(response)
{
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function(error)
{
if(i <= 2)
{
$.toaster({ priority: 'danger', message: error});
}
i++;
});
});
}
vm.overviewDeleted = function() {
employeeFactory.overviewDeleted().then(function(response)
{
if(angular.isDefined(response[0].EmployeeId))
{
vm.employees = response;
}
});
}
vm.delete = function() {
employeeFactory.delete($routeParams.id).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is verwijderd' });
$location.path('/home');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.permanentDelete = function(employeeId) {
employeeFactory.permanentDelete(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is permanent verwijderd' });
$location.path('/prullenbak/werknemers');
}
else
{
angular.forEach(response, function(error)
{
$.toaster({ priority: 'danger', message: error });
});
}
});
}
vm.restore = function(employeeId) {
employeeFactory.restore(employeeId).then(function(response)
{
if(response == 'true')
{
$.toaster({ message: 'De werknemer is teruggezet' });
$location.path('/werknemer/' + employeeId);
}
else
{
if(angular.isArray(response))
{
angular.forEach(response, function(error)
{
$.toaster({ priority : 'danger', message : error[0]});
});
}
}
});
}
<!--ng-init-->
vm.editEmployee = function()
{
vm.show();
vm.overviewDepartments();
vm.overviewInternEducators();
vm.overviewMentors();
vm.overviewSchools();
}
vm.createEmployee = function() {
vm.overviewMentors();
vm.overviewSchools();
vm.overviewDepartments();
vm.overviewInternEducators();
}
<!--redirects-->
vm.editRedirect = function(werknemerId)
{
$location.path('/werknemer/edit/' + werknemerId);
}
vm.showTrashedEmployeeRedirect = function(werknemerId)
{
$location.path('/prullenbak/werknemer/' + werknemerId);
}
}
})()
As you can see I use 2 methods called editEmployee and createEmployee (at the end). I use these 2 with the create employee page and the edit employee page. On both pages there are a couple of comboboxes that have to be loaded. In for example my create employee page I say ng-init="employeeController.createEmployee()" and then those comboboxes are filled.
I know this is not the best approach so how could I do this on a different and better way?
There are several ways to structure you app but the style guide endorsed by the Angular team is maintained by John Papa.
Refer to Angular Style Guide by John Papa.
Based on that:
First I would suggest that you split the create, show, edit and delete functionality into separate controllers. This helps with ensuring each controller does only one single thing.This is in line with the idea of Single Responsibility and Separation of Concerns
Secondly since it seems you are using the controllerAs syntax you wouldn't need to inject scope into your controller.
Here is the code for creating an employee(sth like create-employee.controller.js
(function () {
'use strict';
angular.module('employeeApp').controller('CreateEmployeeController', CreateEmployeeController);
//ngInject is used to help create minify safe version of the file during the build process.
//You should have this somewhere in your build process
/** #ngInject **/
function CreateEmployeeController(constants, departmentFactory, employeeFactory, $location, mentorFactory, schoolFactory) {
var vm = this;
vm.create = create;
getMentors();
getSchools();
getDepartments();
getInternEducators();
function getMentors() {
return mentorFactory.overview(constants.companyid).then(function (response) {
vm.mentors = response;
});
}
function getSchools() {
return schoolFactory.overview(constants.companyid).then(function (response) {
if (angular.isDefined(response[0].SchoolId)) {
vm.schools = response;
}
else {
console.log('leeg!');
}
});
}
function getDepartments() {
return departmentFactory.overview(constants.companyid).then(function (response) {
vm.departments = response;
});
}
function getInternEducators() {
return employeeFactory.overviewInternEducators(constants.companyid).then(function (response) {
vm.internEducators = response;
});
}
}
function create() {
return employeeFactory.create(vm.employee, vm.profilePicture).success(function (response, status) {
if (status == 200) {
$.toaster({message: 'De werknemer is toegevoegd'});
$location.path('/home');
}
}).error(function (response) {
var i = 0;
vm.error = response;
angular.forEach(response.result.message, function (error) {
if (i <= 2) {
$.toaster({priority: 'danger', message: error});
}
i++;
});
});
}
})();
You would then create the other controllers by splitting the functionality following this example.

How to access $http.get caller variable

Consider this simple angularjs code:
$http.get( url ).then(function ( response ) {
var cache = new Cache(url);
cache.response = response;
});
My problem is the above code is nondeterministic. Sometime the url do not match when the response is get from the server.
I would like to edit 10 contact data simultanously.
So for that to work, I would like to cache the requests to the server and put it into a javascript object.
I have written a simple service to achieve that, but suffers from the above bug.
Here is the code:
angular.module('myApp')
.factory('save', function($http, $q) {
// Private object
var Cache = function(url) {
this._url = url;
this.response = {};
this.saveDeferred = null;
this.saveDeferredFulfilled = false;
};
Cache.prototype.$save = function () {
return $http.put( this._url ).then(function (response) {
this.response = response;
return response;
});
};
//public method
var draft = {
caches: {},
get: function ( url ) {
if (draft.caches.hasOwnProperty(url)) {
return draft.caches.url.response;
} else {
return $http.get( url ).then(function ( response ) {
var cache = new Cache(url);
cache.response = response;
return cache;
});
}
},
save: function(url) {
if (draft.caches.url.saveDeferred) {
if (!draft.caches.url.saveDeferredFulfilled) {
draft.caches.url.saveDeferred.reject(new Error('forced timeout'));
}
draft.caches.url.saveDeferred = null;
draft.caches.url.saveDeferredFulfilled = false;
}
draft.caches.url.saveDeferred = $q.defer();
draft.caches.url.response.version = (parseInt(draft.caches.url.response.version) + 1).toString();
$http.put(url, draft.caches.url.response)
.success(function(data) {
console.log('some data returned');
console.log(data);
draft.caches.url.saveDeferredFulfilled = true;
draft.saveDeferred.resolve(data);
})
.error(function(error) {
console.log('Some error occured in save.creates');
console.log(error);
draft.saveDeferred.reject(error);
});
return draft.saveDeferred.promise;
}
};
return draft;
});
It must be something really basic, what I'm missing here.

Value of var goes back to empty after exiting function?

So I have an api request inside of a function thats placed in my Service script.. I have defined the variable "curruser" outside of the function so I can keep its value, however after exiting the follow Scirpt, curruser is empty??
services.js
function fbUserInfo() {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
So the console.log would return the proper JSON object I retrieved from facebook.. but when I return it in the return statement
return {
userInfo: function() {
fbUserInfo();
console.log(curruser);
return curruser;
}
it returns that curruser is an empty object! I did write
var curruser;
into the first line inside the ".factory"
you have to use then() since fbUserInfo() is async function
return {
userInfo: function() {
$.when(fbUserInfo())..then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
}).then(function(){
console.log(curruser);
return curruser;
})
}
Haven't tested this but might work.
var curruser;
function fbUserInfo( callback ) {
ngFB.api({
path: '/me',
params: {
fields: '/*params*/'
}
}).then(
function(user) {
curruser = user;
$http.get(/*send GET request to my server*/).success(function(response) {
if (response.length < 20) {
curruser.firsttime = true;
} else {
curruser.firsttime = false;
}
console.log(curruser);
console.log("1");
callback(curruser);
});
},
function(error) {
alert('Facebook error: ' + error.error_description);
});
}
return {
userInfo: function( callback ) {
fbUserInfo( function(data){
console.log(data);
callback(data);
});
}

AngularJS Type Error

I am brand new to AngularJS and I'm debugging someone else's code. I am getting the following error when I debug in Google Chrome:
TypeError: accountService.logIn(...).success is not a function.
Here is some of my code. The problem is in the signUp form on the line accountService.logIn(signupform).success(function (response) {. If more info is needed please let me know.
Here is my entire controller.
(function () {
'use strict';
angular
.module('vidaexpress')
.controller('accountController', accountController);
accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];
function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
var vm = this;
vm.logIn = logIn;
vm.signUp = signUp;
vm.signOut = signOut;
vm.facebookLogin = facebookLogin;
vm.facebookLogout = facebookLogout;
vm.recoveryPassword = recoveryPassword;
vm.resetPassword = resetPassword;
vm.sendVerifyEmail = sendVerifyEmail;
function logIn(loginform) {
vm.signinloading = true;
accountService.logIn(loginform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.setUserInfo(response);
if (!$rootScope.returncust) {
window.sessionStorage.setItem('returncust', true);
}
vm.isAccountOpen = false;
}
}, function (error) {
toastr.error(error.error);
}).finally(function () {
vm.signinloading = false;
});
}
function signUp(signupform) {
vm.signuploading = true;
accountService.signUp(signupform)
.then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
accountService.logIn(signupform).success(function (response) {
accountService.setUserInfo(response);
logIn();
}).error(function(error) {
toastr.error(error.error);
});
}
},function (error) {
toastr.error('System Error');
}).finally(function () {
vm.signuploading = false;
});
}
function signOut() {
//Log out API
//accountService.logOut();
//Log out Facebook
var userInfo = accountService.getUserInfo();
if (userInfo.facebookLogin) {
facebookLogout();
}
//Log out UI
accountService.setUserInfo(null);
vm.isAccountOpen = false;
$state.go('main.index');
}
function facebookLogin() {
facebookService.login();
}
function facebookLogout() {
facebookService.logout();
}
function recoveryPassword(email) {
accountService.recoveryPassword(email).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('An email has been sent.');
}
}, function () {
toastr.error('System Error');
});
}
function resetPassword(model) {
model.customerId = $stateParams.id;
model.token = $stateParams.token;
accountService.resetPassword(model).then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Your password has been reset.');
}
}, function () {
toastr.error('System Error');
});
}
function sendVerifyEmail() {
accountService.sendVerifyEmail().then(function (response) {
if (response && response.error) {
toastr.error(response.error);
} else {
toastr.success('Email has sent');
}
}, function () {
toastr.error('System Error');
});
}
}
})();
Here is my account.server.js file.
(function () {
'use strict';
angular
.module('vidaexpress')
.service('accountService', accountService);
accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];
function accountService($http, $window, $rootScope, apiUrl) {
var baseUrl = apiUrl.account;
var cookieUser;
var sessionName = 'userInfo';
this.logIn = logIn;
this.logOut = logout;
this.signUp = signUp;
this.setUserInfo = setUserInfo;
this.getUserInfo = getUserInfo;
this.confirm = confirm;
this.recoveryPassword = recoveryPassword;
this.resetPassword = resetPassword;
this.sendVerifyEmail = sendVerifyEmail;
function logIn(credential) {
return $http({
method: 'POST',
url: baseUrl + 'token',
headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
grant_type: 'password',
email: credential.email,
password: credential.password
}
}).then(function (response) {
if (!response) {
return { error: 'System Error' };
} else if (response.error) {
return { error: response.error };
} else {
return response.data;
}
}, function (error) {
return { error: 'System Error' };
});
}
function logout() {
return $http.post(baseUrl + 'logout');
}
function signUp(userInfo) {
return $http.post(baseUrl + 'signup', userInfo);
}
function setUserInfo(userInfo) {
cookieUser = userInfo;
$rootScope.currentUser = userInfo;
$window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
}
function getUserInfo() {
if (!cookieUser) {
cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
}
return cookieUser;
}
function confirm(customerId, token) {
$http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
}
function recoveryPassword(email) {
return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
function resetPassword(model) {
return $http.post(baseUrl + 'resetPassword', model).then(function () {
return null;
}, function(){
return { error: 'System Error' };
});
}
function sendVerifyEmail() {
return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
return null;
}, function () {
return { error: 'System Error.' };
});
}
}
})();
The way your return pattern is working in the service requires your controller to use .then() rather than success()
accountService.logIn(loginform)
.then(function (response) {

Categories

Resources