1

我有一个 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"
  }
}

这是 JSfiddle 示例

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

4

1 回答 1

2

$resource请使用按对象返回的承诺。在这种情况下,您应该使用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;
});
于 2016-03-09T10:36:17.750 回答