I was trying to implement redirection to the new user profile using angularJS; however, I was not able to return user object from Sails Action to angular after the user was successfully created. As a result, I do not have the user id in order to render the page using angular.
I am using default SailsJS architecture.
Here is my Angular code in SignUpController.js (I know that it's not the best idea to make http requests in controller)
angular.module('SignupModule').controller('SignupController', function ($scope, $http, $location) {
$scope.submitSignupForm = function (){
console.log("clicked");
$scope.successMessage = false;
$scope.errorMesaage = false;
$http.post('/signup', {
name: $scope.signupForm.name,
pass: $scope.signupForm.pass
}).then (function onSuccess(res){
$scope.successMessage = true;
// render the profile of a new user
// did not get user object from sails
// res object return status of request but not user object
}).catch(function onError(res){
$scope.errorMesaage = true;
})
}
});
Here is my SailsJS code in UserController.js.( I was trying to return res.send() and res.json() but it doesn't work.)
module.exports = {
//create new user
create: function (req, res, next) {
//check if user exists
User.findOne({name: req.param('name')}).exec(function findOneCB(err, found){
if(err) return next(err);
//if user does not exist create one; otherwise exit
if(!found){
User.create (req.params.all(), function userCreated(err, user){
if(err) return next(err);
/* return user object to angular */
//return res.send(user);
//return res.json(user);
});
} else {
return next();
}
});
}
};
here is config/routes.js
'GET /signup': {
view: 'signup'
},
'POST /signup': {
controller: 'UserController',
action: 'create'
},
The workflow should look something like this:
Thanks! :)
You can do this,
module.exports = {
create: function (req, res) {
User.findOne({name: req.param('name')}).exec(function findOneCB(err, found) {
if (err) return res.negotiate(err);
if (!found) {
User.create(req.params.all(), function userCreated(err, user) {
if (err) res.negotiate({error:err});
return res.ok(user);
});
} else {
return res.negotiate({error:new Error("USER_EXIST")});
}
});
}
};