Angular工厂只返回部分资源响应

时间:2016-03-09 10:32:43

标签: javascript angularjs angular-promise angular-resource angular-providers

我有一个Angular工厂DogePrice

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

典型的api响应是这样的:

{
  "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

如何创建仅返回data.price字段的工厂?我想要一个只有$scope.price = DogePrice.get();或类似东西的干净控制器。

1 个答案:

答案 0 :(得分:2)

使用$resource对象的promise返回。在这种情况下,您应该使用promise模式从工厂获取数据。

<强>工厂

.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
   }
}])

<强>控制器

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