为什么我的工厂没有退货?

时间:2015-07-04 19:09:55

标签: angularjs

我正在制作一个简单的天气应用程序。我正在将我的逻辑整合到一个工厂中,但它什么都没有返回。请帮忙。

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;
            });
        }
    }
}])

1 个答案:

答案 0 :(得分:1)

您无法从ajax请求等异步操作返回。但是,您可以返回promise object,以便在加载数据时对其进行排序:

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;
            })
        }
    }
}]);

注意,工厂方法现在返回$http.jsonp调用的结果,即Promise对象。

现在在控制器中,您可以通过使用then方法提供回调来使用它:

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

另外,请务必阅读并理解How do I return the response from an asynchronous call?

相关问题