neptune
neptune

Reputation: 1261

Angular factory returning only part of resource response

I have an Angular factory DogePrice:

.factory('DogePrice', ['$resource', function ($resource) {
    return $resource("https://chain.so/api/v2/get_info/DOGE");
}])

The typical api response is like this:

{
  "status" : "success",
  "data" : {
    "name" : "Dogecoin",
    "acronym" : "DOGE",
    "network" : "DOGE",
    "symbol_htmlcode" : "Ð",
    "url" : "http://www.dogecoin.com/",
    "mining_difficulty" : "18661.80200222",
    "unconfirmed_txs" : 7,
    "blocks" : 1119625,
    "price" : "0.00000046",
    "price_base" : "BTC",
    "price_update_time" : 1453938374,
    "hashrate" : "1289658619826"
  }
}

Here is the JSfiddle example

How can I create a factory that only returns the data.price field? I'd like to have a clean controller with only $scope.price = DogePrice.get(); or something similar.

Upvotes: 1

Views: 123

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

Do use promise return by $resource object. In that case you should use promise pattern to get data from the factory.

Factory

.factory('DogePrice', ['$resource', function ($resource) {
   var myResource = $resource("https://chain.so/api/v2/get_info/DOGE")
   var getData = function(){
      return myResource.get().$promise.then(function(response){
          //here you have control over response
          //you could return whatever you want from here
          //also you could manipulate response OR validate data
          return response.data;
      });
   } 
   return {
     getData: getData
   }
}])

Controller

DogePrice.getData().then(function(data){
   $scope.price = data;
});

Upvotes: 2

Related Questions