简体   繁体   中英

angularjs - Trouble returning data from a factory

I'm trying to create a db factory that returns data from the database to the client after the data is successfuly posted but it returns as 'undefined' for some reason.

My factory function looks like this:

uno.factory('adbFactory', ['$http', function($http){

    var fact = {};

    fact.get = function(http, query, isAll) {
        //var query = "get all blog_posts";
        http.post('php/adb/adb.php', {'query': query, 'all': isAll})
        .success(function(data){
            //console.log(data);
            return data;
        })
        .error(function(){
            console.log('Error...');
        });
    };

    return fact;

}]);

And my controller resembles this:

uno.controller('newsCtrl', function($scope, $http, adbFactory){
    $scope.derp = 'derp!!!!!';
    console.log(adbFactory.get($http, 'get users 1', false));
});

don't worry about the 'get users 1 etc etc' string, i created a function in php that renders a SQL query based on given parameters. Is there something in my factory code i need to improve on??

I would advice returning the promise from the factory and handling the success and error events in the controller instead.

fact.get = function(http, query, isAll) {
    return http.post('php/adb/adb.php', {'query': query, 'all': isAll});
};

uno.controller('newsCtrl', function($scope, $http, adbFactory){
   adbFactory.get($http, 'get users 1', false).success(function(data) {
       console.log(data);
   });
});

fact.get method has no return statement, that's why it returns undefined .

Also, this callback is useless because it is called asynchronously

.success(function(data){
   //console.log(data);
   return data;
 })

I think you want somethig like:

fact.get = function(http, query, isAll) {
   return http.post('php/adb/adb.php', {'query': query, 'all': isAll});
};


uno.controller('newsCtrl', function($scope, $http, adbFactory){    

    adbFactory
    .get($http, 'get users 1', false)
    .success(function(data){
         console.log(data);
     })
     .error(function(){
         console.log('Error...');
     });

});

You have to keep in mind that you are performing some asynchronous request.

You have two way to retrieve your data :

  • Following the callback way
  • Following the promise way

As you know, $http service return promise, and has some callback method, like .success() and .then() for example.

For promise, $q.defer() is a promise manager from the deferred API .

$q.defer() get 2 methods :

  • resolve(value) : which resolve our associated promise, by giving her the final value

  • reject(reason) : which resolve an promise error.

So you can do :

Service

(function(){

  function Service($http, $q){

    var defer = $q.defer();

    //Callback way
    function get(callback){
      $http.get('app.php').success(function(data){
        //Pass our data to the callback
        callback(data);
      });
    }

    //Promise ways
    function getPromise(){
      $http.get('app.php').success(function(data){
        //Resolve the data
        defer.resolve(data);
      });
      //Return our promise
      return defer.promise;
    }

    return {
      get: get,
      getPromise: getPromise
    };

  }

  angular
    .module('app')
    .factory('Service', Service);

})();

Controller

(function(){

function Controller($scope, Service) {

  //Our callback method
  function print(data){
      console.log(data);
  }

  //Retrieve our data by using callback way
  Service.get(print);


  //Retrieve our data by using promise way
  var promise = Service.getPromise();

  //When promise is resolved
  promise.then(function(data){
    //Retrieve our data
    console.log(data);
  });

}

angular
.module('app', [])
.controller('ctrl', Controller);

})();

But what should i use ? I think that use promise is better than callback, because you can handle easily your request. Moreover, you can perform promise chaining , and avoid the famous callback hell .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM