2016-02-05 85 views
2

無論我做什麼,我總是從我的工廠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; 
    }); 
}); 
+0

嘗試更改爲' deferred.resolve(res.data)'。第一個'res'是承諾對象 – charlietfl

回答

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

}]); 
+0

第一個沒有返回 – charlietfl

+0

第二個關於 –

+0

關閉但第一個'$ http'的'then'返回一個promise對象,'data'是該對象的屬性 – charlietfl