从工厂返回控制器$http承诺时未定义

Undefined when returning $http promise in controller from factory

本文关键字:承诺 未定义 http 工厂 返回 控制器      更新时间:2023-09-26

无论我做什么,我总是从工厂API调用中得到$$stateundefined。我尝试过承诺,只是简单地从.then那里返回response.data,但我尝试过的都没有奏效。

我可以将正确的响应数据放入我的控制器中,但是当我尝试将其分配给任何内容时,我只会得到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; 
    });
});

我认为你不需要使用$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
     })
}]);