簡體   English   中英

角工廠僅返回部分資源響應

[英]Angular factory returning only part of resource response

我有一個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();的干凈控制器$scope.price = DogePrice.get(); 或類似的東西。

不要使用$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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM