javascript - Undefined when returning $http promise in controller from factory -
no matter $$state
or undefined
factory api call. i've tried promises , returning response.data
.then
nothing tried works.
i can proper response data controller when try assign undefined
or $$state
, depending on method use.
my factory:
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; });
my controller:
controller('forecastcontroller', function ($scope, $location, forecastfactory, locationservice) { vm = this; forecastfactory.getforecast('chicago, il').then(function (res) { console.log(res); vm.forecast = res; }); });
i think don't need use $q
because $http returns promise,
you can do
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 }); }
and in controller, same doing now
other way return promise returned $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' } }) }
and in controller this
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){ // }) }]);
Comments
Post a Comment