ksa_coder
ksa_coder

Reputation: 1413

AngularJS Factory return type undefined

I am attempting to store data in the database within an angularjs factory, and that is working for me. After storing data in Parse, I am trying to return either 1 or the error object (depending if store worked or not) and then handling that in the controller.

In the controller when I check the returned value, it neither 1 or error, but rather undefined.

Here is the code I have...

Controller Calling Service:

$scope.signup = function(user, $state) {

        if(user !== null)
        {
            var returnValue = CreateUserService.createAccount(user); 
            console.log("Return Value = " + returnValue);
            if(returnValue === 1)
            {
                $state.go('activate');   
            }else{
                console.log("Return Value was not appropriate");   
            }
        }else{
            console.log("Something went wrong while adding user");   
        }

    };

Factory:

.factory('CreateUserService', function() {
    return {
      createAccount: function(user) {
          var parseUser = new Parse.User();
          parseUser.set("username", user.username);
          parseUser.set("email", user.email);
          parseUser.set("name", user.name);
          parseUser.set("password", user.password);
          parseUser.set("mobile", user.mobile);

          /*Attempt to create user in DB*/
          parseUser.signUp(null, {
            success: function(parseUser) {
              // Hooray! Let them use the app now.
              //alert("success!");
              console.log("Stored");
                return 1;
            },
            error: function(parseUser, error) {
              // Show the error message somewhere and let the user try again.
              //alert("Error: " + error.code + " " + error.message);
              console.log("Error: " + error.message );    
              return error;
            }
          });
      }
    }
}

Thanks for helping out.

Upvotes: 0

Views: 255

Answers (3)

Shaun
Shaun

Reputation: 927

You don't actually return from the createAccount function, only from the callbacks. Also the callbacks are asynchronous so it will return before it has completed the request.

.factory('CreateUserService', function($q) {
    return {
      createAccount: function(user) {
          var deferred = $q.defer();
          var parseUser = new Parse.User();
          parseUser.set("username", user.username);
          parseUser.set("email", user.email);
          parseUser.set("name", user.name);
          parseUser.set("password", user.password);
          parseUser.set("mobile", user.mobile);

          /*Attempt to create user in DB*/
          parseUser.signUp(null, {
            success: function(parseUser) {
              // Hooray! Let them use the app now.
              //alert("success!");
              console.log("Stored");
              deferred.resolve(1);
            },
            error: function(parseUser, error) {
              // Show the error message somewhere and let the user try again.
              //alert("Error: " + error.code + " " + error.message);
              console.log("Error: " + error.message );    
              deferred.reject(error);
            }
          });

          return deferred.promise;
      }
    }
}

Then in your controller use the service function as a promise.

CreateUserService.createAccount(user).then(function(result) { 
   // result should be whatever passed in to resolve
}, function(error) {
  // error here will be whatever passed into reject
});

Learn more about promises: https://docs.angularjs.org/api/ng/service/$q

Upvotes: 1

jsNovice
jsNovice

Reputation: 646

The issue is that you are returning from a callback one step deep, so you need some sort of callback or angularJS's $q service

Similar issue: How to return value from an asynchronous callback function?

 $scope.signup = function(user, $state) {

    if(user !== null)
    {
        // notice the callback function passed below

        CreateUserService.createAccount(user, function(returnValue){

            // returnValue in available here for use

            console.log("Return Value = " + returnValue);
            if(returnValue === 1)
            {
                $state.go('activate');   
            }else{
                console.log("Return Value was not appropriate");   
            }
        });
    }else{
        console.log("Something went wrong while adding user");   
    }
};

Factory:

    .factory('CreateUserService', function() {
    return {
      createAccount: function(user, done) {

         // done callback function in the param to be called for returning the values 

          var parseUser = new Parse.User();
          parseUser.set("username", user.username);
          parseUser.set("email", user.email);
          parseUser.set("name", user.name);
          parseUser.set("password", user.password);
          parseUser.set("mobile", user.mobile);

          /*Attempt to create user in DB*/
          parseUser.signUp(null, {
            success: function(parseUser) {
              // Hooray! Let them use the app now.
              //alert("success!");
              console.log("Stored");

              // call the done/callback here for success
                done(1);

            },
            error: function(parseUser, error) {
              // Show the error message somewhere and let the user try again.
              //alert("Error: " + error.code + " " + error.message);
              console.log("Error: " + error.message );    

              // call the done/callback here for error
              done(error);

            }
          });
      }
    }
}

Upvotes: 1

Sandeeproop
Sandeeproop

Reputation: 1776

I think issue is because of your ajax call asynchronous call. when you are calling "CreateUserService.createAccount(user)", it in turns call ajax call parseUser.signUp which is asynchronous.

.factory('CreateUserService', function($q) {
return {
  createAccount: function(user) {
      var parseUser = new Parse.User();
      parseUser.set("username", user.username);
      parseUser.set("email", user.email);
      parseUser.set("name", user.name);
      parseUser.set("password", user.password);
      parseUser.set("mobile", user.mobile);
      var deferred = $q.defer();  
      /*Attempt to create user in DB*/
      parseUser.signUp(null, {
        success: function(parseUser) {
          // Hooray! Let them use the app now.
          //alert("success!");
          console.log("Stored");
           // return 1;
           deferred.resolve(data);
        },
        error: function(parseUser, error) {
          // Show the error message somewhere and let the user try again.
          //alert("Error: " + error.code + " " + error.message);
          console.log("Error: " + error.message );    
          //return error;
          return deferred.resolve("Error while saving");
        }
      });
      return deferred.promise;
     }
   }
 }

Change your controller also with this $scope.signup = function(user, $state) {

    if(user !== null)
    {
        var promise = CreateUserService.createAccount(user);
            promise.then(function(data) {
            $state.go('activate');
          },
          function(data) {
            console.log("Return Value was not appropriate");   
        });
    }else{
        console.log("Something went wrong while adding user");   
    }

};

This might resolve the issue

Upvotes: 1

Related Questions