Reputation: 1261
I have this simple app witha factory and a controller:
angular.module('AppName', ['ngResource'])
.factory('apiData', ['$resource', function ($resource) {
var apiRequest = $resource("https://live.reddcoin.com/api/addr/:address/balance");
return {
full: function(address){
return apiRequest.get({address: address}).$promise
.then(
function(data){ console.log(data); return data;},
function(){ return 'error'; }
);
}
}
}])
.controller('TwoController', function($scope, apiData){
$scope.price = apiData.full('RszZrK51ur5G67y3Wy6niTnawdYYdBRZEq').then(function(data){console.log(data); return data;});
});
The then sections in both factory and controller not returning data from the api resource. Instead it returns e { $promise=Promise, $resolved=true, toJSON=function(), more...}
as can be seen in the console.
The url from the example api resource: https://live.reddcoin.com/api/addr/RszZrK51ur5G67y3Wy6niTnawdYYdBRZEq/balance
Upvotes: 2
Views: 540
Reputation: 136194
I'm not sure why $resource
doesn't include data(not in object format) inside object return by promise, It display result like below
e {$promise: Promise, $resolved: true} // 1003021043401956 isn't included there
I think get request is expecting object returned from the server. So if it doesn't return an object, then it will not include the same in response
There are 2 ways to solve this problem.
{'data': '1003021043401956'}
Create your own get
request object inside resource, that will modify before it returns promise object.
var apiRequest = $resource("https://live.reddcoin.com/api/addr/:address/balance", {}, {
get: {
method: 'GET',
transformResponse: function(response){
return {data: response}; //creating object
}
}
});
Upvotes: 2
Reputation: 5822
Try this:
.controller('TwoController', function($scope, apiData){
apiData.full('RszZrK51ur5G67y3Wy6niTnawdYYdBRZEq').then(function(data){
console.log(data);
$scope.price = data;
});
});
Remember that promises are chained. So eventhough you return data
in the success callback, the result of then
is still a promise (with data
as the inner result).
Working code snippet:
angular.module('AppName', ['ngResource'])
.factory('apiData', ['$resource', function ($resource) {
var apiRequest = $resource("https://live.reddcoin.com/api/addr/:address/balance");
return {
full: function(address){
return apiRequest.get({address: address}).$promise
.then(
function(data){ console.log(data); return data;},
function(){ return 'error'; }
);
}
}
}])
.controller('TwoController', function($scope, apiData){
apiData.full('RszZrK51ur5G67y3Wy6niTnawdYYdBRZEq').then(function(data){console.log(data); $scope.price = data;});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.23/angular-resource.min.js"></script>
<div ng-app="AppName" ng-controller="TwoController">{{price}}</div>
Upvotes: 1