jquery - Angular: deferred var is undefined in then-method -
within angular.js code i'm calling yahoo yql api get/jsonp , response. there 2 problems.
- it calls error method instead of success. why?
- the deferred variable seems undefined within error-function. why?
you can find jsfiddle here. based on ajax example.
function defaultctrl($log, $scope, $http, myservice) { var promise = myservice.getsuggestions('yahoo'); promise.then( function(payload) { $log.info('receiving data', payload); $scope.test = payload; $log.info('received data', payload); }, function(errorpayload) { $log.error('failure loading suggestions', errorpayload); }); } angular.module('mymodule', []) .factory('myservice', function ($http, $log, $q) { return { getsuggestions: function (symbol) { var deferred = $q.defer(); $http.jsonp("http://d.yimg.com/autoc.finance.yahoo.com/autoc", { cache: true, params: { callback: "yahoo.finance.symbolsuggest.sscallback", query: symbol } }) .success(function(data) { deferred.resolve(data); }) .error(function(msg, code) { $log.error("error"); deferred.reject(msg); // <---- error occurs here! $log.error(msg, code); }); var yahoo = window.yahoo = {finance: {symbolsuggest: {}}}; yahoo.finance.symbolsuggest.sscallback = function (data) { $log.info("received data", data); }; // yahoo.finance return deferred.promise; } } });
here working example. have pass callback function in promise callback , have callback reject or resolve promise. think problem code posted that, after execution of callback success
, error
both executed , result undefined var resolved/rejected.
var myapp = angular.module('mymodule', []); myapp.controller('defaultctrl', function ($log, $scope, $http, myservice) { var promise = myservice.getsuggestions('yahoo'); promise.then( function (payload) { $log.info('receiving data in defaultctrl', payload); $scope.test = payload; }, function (errorpayload) { $log.error('failure loading suggestions', errorpayload); }); }); myapp.factory('myservice', function ($http, $log, $q) { return { getsuggestions: function (symbol) { var yahoo = window.yahoo = { finance: { symbolsuggest: {} } }; yahoo.finance.symbolsuggest.sscallback = function (data) { $log.info("received data in sscallback", data); deferred.resolve(data); }; // yahoo.finance var deferred = $q.defer(); $http.jsonp("http://d.yimg.com/autoc.finance.yahoo.com/autoc", { cache: true, params: { callback: "yahoo.finance.symbolsuggest.sscallback", query: symbol } }) .then(yahoo.finance.symbolsuggest.sscallback); return deferred.promise; } } });
Comments
Post a Comment