Within my Angular.JS code I'm calling the Yahoo YQL API with GET/JSONP and I do get a response. But there are two problems.
- It calls the error method instead of success. Why?
- The deferred variable seems to be undefined within the error-function. Why?
You can find the JsFiddle here. It is based on an 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 is a working example. You have to pass the callback function in the promise callback and then have your callback reject or resolve the promise. I think the problem with the code you posted is that, after the execution of your callback the
success
anderror
are both executed and as a result an undefined var was resolved/rejected.