我有一个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"
}
}
如何创建仅返回data.price
字段的工厂?我想要一个只有$scope.price = DogePrice.get();
或类似东西的干净控制器。
答案 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;
});