Search code examples
javascriptangularjsangularjs-factory

How can I get specific results from a factory?


I'm just learning angularjs and I'm strugling to get the results I want from this factory :

app.factory('foreCast', ['$http', function($http,$scope ) { 

var req = $http.jsonp("https://www.kimonolabs.com/api/c1ab8xnw?&apikey=api-key&callback=JSON_CALLBACK");
     req.success(function (data) { 
         req.rows =data.results.collection1;
          req.rand =req.rows[Math.floor(Math.random() * req.rows.length)];
              console.log(req.rand); 
                 //i want this results      
                                       });    
return req; //how can i return req.rand?

}]);

Solution

  • app.factory('foreCast', ['$q', '$http', function ($q, $http) {
        return {
            getRand: function () {
                var deferred = $q.defer();
    
                $http
                    .jsonp("https://www.kimonolabs.com/api/c1ab8xnw?&apikey=api-key&callback=JSON_CALLBACK")
                    .then(function (response) {
                        var rows = response.data.results.collection1;
                        var rand = rows[Math.floor(Math.random() * rows.length)];
                        deferred.resolve(rand);
                    }, function (err) {
                        deferred.reject(err);
                    })
                    return deferred.promise;
                }
            }
    }])
    

    And then from controller for exemple use it like this :

    foreCast.getRand().then(function(rand){
        var myRand = rand;
    })