1

I am making a simple weather app. I am consolidating my logic into a factory, but it is returning nothing. Please help.

var app = angular.module('APP',[]);
app.controller('TheCtrl',function(weatherFetch, $scope, $http){
    $http.get('states.json?callback=JSON_CALLBACK').success(function(data){
        $scope.states = data
    });
    $scope.weather = function(s,c){
        console.log(weatherFetch.weatherFetch(s,c));
    }
})

app.factory('weatherFetch', ['$http', function($http){
    return{
        weatherFetch : function(s,c){
            $http.jsonp('http://api.wunderground.com/api/80ba6707f58c665f/conditions/q/'+s.toUpperCase()+'/'+c.toUpperCase().replace(/ /g,"_")+'.json?callback=JSON_CALLBACK')
            .success(function(data){
                return data;
            }).error(function(err){
                return err;
            });
        }
    }
}])
Okku
  • 7,468
  • 4
  • 30
  • 43
uoflcards20
  • 55
  • 1
  • 5

1 Answers1

1

You can't return from asynchronous operations like ajax requests. However, you can return promise object that will allow to sort of subscribe to data when it's loaded:

app.factory('weatherFetch', ['$http', function ($http) {
    return {
        weatherFetch: function (s, c) {
            return $http.jsonp('http://api.wunderground.com/api/80ba6707f58c665f/conditions/q/' + s.toUpperCase() + '/' + c.toUpperCase().replace(/ /g, "_") + '.json?callback=JSON_CALLBACK').success(function (data) {
                return data;
            })
            .error(function (err) {
                return err;
            })
        }
    }
}]);

Note, that factory method now returns result of $http.jsonp invocation, which is Promise object.

Now in controller you would use it as follows by providing callback with then method:

$scope.weather = function (s, c) {
    weatherFetch.weatherFetch(s, c).then(function(data) {
        console.log(data);
    });
}

Also make sure you read and understand How do I return the response from an asynchronous call?

Community
  • 1
  • 1
dfsq
  • 191,768
  • 25
  • 236
  • 258