从工厂返回控制器中的$ http promise时未定义

时间:2016-02-05 23:23:58

标签: javascript angularjs state

无论我做什么,我总是从我的工厂API调用中获取$$stateundefined。我已经尝试过承诺,只是从response.data返回.then,但我没有尝试过。

我可以将正确的响应数据输入到我的控制器中,但是当我尝试将其分配给任何我只是undefined$$state时,取决于我使用的方法。

我的工厂:

factory('forecastFactory', function ($http, $q, SundialConfig) {
    var Forecast = {}; 
    var weatherKey = SundialConfig.openWeatherKey;

    Forecast.dayCnt = 1; 
    Forecast.prepareCity = function (city) {
        city === undefined ? city = 'Chicago, IL' : city = city;
        return city; 
    }

    Forecast.getForecast = function (city) {
        var preparedCity = Forecast.prepareCity(city);
        var deferred = $q.defer();

        $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
            params: {
                appid: weatherKey,
                q: preparedCity,
                cnt: Forecast.dayCnt,   
                callback: 'JSON_CALLBACK'
            }
        })
        .then(function (res) {
            console.log("success");
            deferred.resolve(res);
        })
        .catch(function (err) {
            console.log('error');
        });

        return deferred.promise; 
    }

    return Forecast;
}); 

我的控制器:

controller('ForecastController', function ($scope, $location, forecastFactory, locationService) { 
    vm = this; 
    forecastFactory.getForecast('Chicago, IL').then(function (res) {
        console.log(res);
        vm.forecast = res; 
    });
});

1 个答案:

答案 0 :(得分:3)

我认为您不需要使用$q,因为$ http会返回一个承诺,

你可以做到

Forecast.getForecast = function(city) {
        var preparedCity = Forecast.prepareCity(city);
        return $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
            params: {
                appid: weatherKey,
                q: preparedCity,
                cnt: Forecast.dayCnt,   
                callback: 'JSON_CALLBACK'
            }
        })
        .then(function(res) {
      console.log("success");
      return res.data;

    })

    .catch(function(err) {
      console.log('error')
      return []; // or {} depending upon required data
    });
    }

并在控制器中,按照您现在的行为进行操作

其他方式只是返回$ http

返回的承诺
Forecast.getForecast = function(city) {
        var preparedCity = Forecast.prepareCity(city);

        return $http.jsonp('http://api.openweathermap.org/data/2.5/forecast/daily?', {
            params: {
                appid: weatherKey,
                q: preparedCity,
                cnt: Forecast.dayCnt,   
                callback: 'JSON_CALLBACK'
            }
        }) 
    }

并在控制器中执行此操作

Sundial.Controllers.

controller('ForecastController', ['$scope', '$location', 'forecastFactory', 'locationService', function($scope, $location, forecastFactory, locationService) { 

    vm = this; 

    forecastFactory.getForecast('Chicago, IL').then(function(res) {
        console.log(res)
        vm.forecast = res.data; 
    }, function(err){
          // do something
     })

}]);