無論我做什麼,我總是從我的工廠API調用中獲取$$state
或undefined
。我已經嘗試過承諾,並簡單地從.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;
});
});
嘗試更改爲' deferred.resolve(res.data)'。第一個'res'是承諾對象 – charlietfl