0

如果这听起来像一个愚蠢的问题/尴尬的措辞,请原谅我,所以我的服务函数如下,我在函数之外有一个数组变量

    var newUsdToForeignRates = [];

然后功能如下,

function refresh() {
for(var i =0;i<shortArrays.length;i++){
  var url = YAHOO_FINANCE_URL_PATTERN.
  replace('PAIRS', 'USD' + shortArrays[i].join('","USD'));

   //ajax call to yql query
   $http.jsonp(url).success(function(data) {
    if(data.query.results.rate){
     angular.forEach(data.query.results.rate, function(rate) {
         var currency = rate.id.substring(3,6);
         newUsdToForeignRates.push(rate);

         //Array with all values :- working fine
         console.log(newUsdToForeignRates);
         // result [object,object,....etc];
     });
    }
   });
}

// this always null
console.log(newUsdToForeignRates);
// result  []  -- null
return newUsdToForeignRates;
}

提前致谢

更新


这是完整的代码..

angular.module('exchangeRate',[]).factory('serviceobject',['$http',function($http){
var YAHOO_FINANCE_URL_PATTERN =
      'http://query.yahooapis.com/v1/public/yql?q=select * from '+
      'yahoo.finance.xchange where pair in ("PAIRS")&format=json&'+
      'env=store://datatables.org/alltableswithkeys&callback=JSON_CALLBACK';
var currencieNames =new Array();
var newUsdToForeignRates = [];
var currencies = [
     {"id":"AED","name":"United Arab Emirates Dirham (AED)"},
     {"id":"AFN","name":"Afghan Afghani (AFN)"},
     {"id":"ALL","name":"Albanian Lek (ALL)"},
     {"id":"AMD","name":"Armenian Dram (AMD)"},{"id":"ANG","name":"Netherlands               Antillean"},{"id":"AOA","name":"Angolan Kwanza (AOA)"},{"id":"ARS","name":"Argentine Peso (ARS)"},{"id":"AUD","name":"Australian Dollar (A$)"},{"id":"AWG","name":"Aruban Florin (AWG)"},{"id":"AZN","name":"Azerbaijani Manat (AZN)"},{"id":"BAM","name":"Bosnia-Herzegovina Convertible Mark (BAM)"},{"id":"BBD","name":"Barbadian Dollar (BBD)"},{"id":"BDT","name":"Bangladeshi Taka (BDT)"},{"id":"BGN","name":"Bulgarian Lev (BGN)"},{"id":"BHD","name":"Bahraini Dinar (BHD)"},{"id":"BIF","name":"Burundian Franc (BIF)"},{"id":"BMD","name":"Bermudan Dollar (BMD)"},{"id":"BND","name":"Brunei Dollar (BND)"},{"id":"BOB","name":"Bolivian Boliviano (BOB)"},{"id":"BRL","name":"Brazilian Real (R$)"},{"id":"BSD","name":"Bahamian Dollar (BSD)"},{"id":"BTN","name":"Bhutanese Ngultrum (BTN)"},{"id":"BWP","name":"Botswanan Pula (BWP)"},{"id":"BYR","name":"Belarusian Ruble (BYR)"},{"id":"BZD","name":"Belize Dollar (BZD)"},{"id":"CAD","name":"Canadian Dollar (CA$)"},{"id":"CDF","name":"Congolese Franc (CDF)"},{"id":"CHF","name":"Swiss Franc (CHF)"},{"id":"CLF","name":"Chilean Unit of Account (UF) (CLF)"},{"id":"CLP","name":"Chilean Peso (CLP)"},{"id":"CNH","name":"CNH (CNH)"},{"id":"CNY","name":"Chinese Yuan (CN¥)"},{"id":"COP","name":"Colombian Peso (COP)"},{"id":"CRC","name":"Costa Rican Colón (CRC)"},{"id":"CUP","name":"Cuban Peso (CUP)"},{"id":"CVE","name":"Cape Verdean Escudo (CVE)"},{"id":"CZK","name":"Czech Republic Koruna (CZK)"},{"id":"DEM","name":"German Mark (DEM)"},{"id":"DJF","name":"Djiboutian Franc (DJF)"},{"id":"DKK","name":"Danish Krone (DKK)"},{"id":"DOP","name":"Dominican Peso (DOP)"},{"id":"DZD","name":"Algerian Dinar (DZD)"},{"id":"EGP","name":"Egyptian Pound (EGP)"},{"id":"ERN","name":"Eritrean Nakfa (ERN)"},{"id":"ETB","name":"Ethiopian Birr (ETB)"},{"id":"EUR","name":"Euro (€)"},{"id":"FIM","name":"Finnish Markka (FIM)"},{"id":"FJD","name":"Fijian Dollar (FJD)"},{"id":"FKP","name":"Falkland Islands Pound (FKP)"},{"id":"FRF","name":"French Franc (FRF)"},{"id":"GBP","name":"British Pound Sterling (£)"},{"id":"GEL","name":"Georgian Lari (GEL)"},{"id":"GHS","name":"Ghanaian Cedi (GHS)"},{"id":"GIP","name":"Gibraltar Pound (GIP)"},{"id":"GMD","name":"Gambian Dalasi (GMD)"},{"id":"GNF","name":"Guinean Franc (GNF)"},{"id":"GTQ","name":"Guatemalan Quetzal (GTQ)"},{"id":"GYD","name":"Guyanaese Dollar (GYD)"},{"id":"HKD","name":"Hong Kong Dollar (HK$)"},{"id":"HNL","name":"Honduran Lempira (HNL)"},{"id":"HRK","name":"Croatian Kuna (HRK)"},{"id":"HTG","name":"Haitian Gourde (HTG)"},{"id":"HUF","name":"Hungarian Forint (HUF)"},{"id":"IDR","name":"Indonesian Rupiah (IDR)"},{"id":"IEP","name":"Irish Pound (IEP)"},{"id":"ILS","name":"Israeli New Sheqel"},{"id":"INR","name":"Indian Rupee (Rs.)"},{"id":"IQD","name":"Iraqi Dinar (IQD)"},{"id":"IRR","name":"Iranian Rial (IRR)"},{"id":"ISK","name":"Icelandic Króna (ISK)"},{"id":"JMD","name":"Jamaican Dollar (JMD)"},{"id":"JOD","name":"Jordanian Dinar (JOD)"},{"id":"JPY","name":"Japanese Yen (¥)"},{"id":"KES","name":"enyan Shilling (KES)"},{"id":"KGS","name":"Kyrgystani Som (KGS)"},{"id":"KHR","name":"Cambodian Riel (KHR)"},{"id":"KMF","name":"Comorian Franc (KMF)"},{"id":"KPW","name":"North Korean Won (KPW)"},{"id":"KRW","name":"South Korean Won (?)"},{"id":"KWD","name":"Kuwaiti Dinar (KWD)"},{"id":"KYD","name":"Cayman Islands Dollar (KYD)"},{"id":"KZT","name":"Kazakhstani Tenge (KZT)"},{"id":"LAK","name":"Laotian Kip (LAK)"},{"id":"LBP","name":"Lebanese Pound (LBP)"},{"id":"LKR","name":"Sri Lankan Rupee (LKR)"},{"id":"LRD","name":"Liberian Dollar (LRD)"},{"id":"LSL","name":"Lesotho Loti (LSL)"},{"id":"LTL","name":"Lithuanian Litas (LTL)"},{"id":"LVL","name":"Latvian Lats (LVL)"},{"id":"LYD","name":"Libyan Dinar (LYD)"},{"id":"MAD","name":"Moroccan Dirham (MAD)"},{"id":"MDL","name":"Moldovan Leu (MDL)"},{"id":"MGA","name":"Malagasy Ariary (MGA)"},{"id":"MKD","name":"Macedonian Denar (MKD)"},{"id":"MMK","name":"Myanma Kyat (MMK)"},{"id":"MNT","name":"Mongolian Tugrik (MNT)"},{"id":"MOP","name":"Macanese Pataca (MOP)"},{"id":"MRO","name":"Mauritanian Ouguiya (MRO)"},{"id":"MUR","name":"Mauritian Rupee (MUR)"},{"id":"MVR","name":"Maldivian Rufiyaa (MVR)"},{"id":"MWK","name":"Malawian Kwacha (MWK)"},{"id":"MXN","name":"Mexican Peso (MX$)"},{"id":"MYR","name":"Malaysian Ringgit (MYR)"},{"id":"MZN","name":"Mozambican Metical (MZN)"},{"id":"NAD","name":"Namibian Dollar (NAD)"},{"id":"NGN","name":"Nigerian Naira (NGN)"},{"id":"NIO","name":"Nicaraguan Córdoba (NIO)"},{"id":"NOK","name":"Norwegian Krone (NOK)"},{"id":"NPR","name":"Nepalese Rupee (NPR)"},{"id":"NZD","name":"New Zealand Dollar (NZ$)"},{"id":"OMR","name":"Omani Rial (OMR)"},{"id":"PAB","name":"Panamanian Balboa (PAB)"},{"id":"PEN","name":"Peruvian Nuevo Sol (PEN)"},{"id":"PGK","name":"Papua New Guinean Kina (PGK)"},{"id":"PHP","name":"Philippine Peso (Php)"},{"id":"PKG","name":"PKG (PKG)"},{"id":"PKR","name":"Pakistani Rupee (PKR)"},{"id":"PLN","name":"Polish Zloty (PLN)"},{"id":"PYG","name":"Paraguayan Guarani (PYG)"},{"id":"QAR","name":"Qatari Rial (QAR)"},{"id":"RON","name":"Romanian Leu (RON)"},{"id":"RSD","name":"Serbian Dinar (RSD)"},{"id":"RUB","name":"Russian Ruble (RUB)"},{"id":"RWF","name":"Rwandan Franc (RWF)"},{"id":"SAR","name":"Saudi Riyal (SAR)"},{"id":"SBD","name":"Solomon Islands Dollar (SBD)"},{"id":"SCR","name":"Seychellois Rupee (SCR)"},{"id":"SDG","name":"Sudanese Pound (SDG)"},{"id":"SEK","name":"Swedish Krona (SEK)"},{"id":"SGD","name":"Singapore Dollar (SGD)"},{"id":"SHP","name":"Saint Helena Pound (SHP)"},{"id":"SLL","name":"Sierra Leonean Leone (SLL)"},{"id":"SOS","name":"Somali Shilling (SOS)"},{"id":"SRD","name":"Surinamese Dollar (SRD)"},{"id":"STD","name":"Sao Tomé and Príncipe Dobra (STD)"},{"id":"SVS","name":"alvadoran Colón (SVC)"},{"id":"SYP","name":"Syrian Pound (SYP)"},{"id":"SZL","name":"Swazi Lilangeni (SZL)"},{"id":"THB","name":"Thai Baht (?)"},{"id":"TJS","name":"Tajikistani Somoni (TJS)"},{"id":"TMT","name":"Turkmenistani Manat (TMT)"},{"id":"TND","name":"Tunisian Dinar (TND)"},{"id":"TOP","name":"Tongan Pa?anga (TOP)"},{"id":"TRY","name":"Turkish Lira (TRY)"},{"id":"TTD","name":"Trinidad and Tobago Dollar (TTD)"},{"id":"TWD","name":"New Taiwan Dollar (NT$)"},{"id":"TZS","name":"Tanzanian Shilling (TZS)"},{"id":"UAH","name":"Ukrainian Hryvnia (UAH)"},{"id":"UGX","name":"Ugandan Shilling (UGX)"},{"id":"USD","name":"US Dollar ($)"},{"id":"UYU","name":"Uruguayan Peso (UYU)"},{"id":"UZS","name":"Uzbekistan Som (UZS)"},{"id":"VEF","name":"Venezuelan Bolívar (VEF)"},{"id":"VND","name":"Vietnamese Dong (?)"},{"id":"VUV","name":"Vanuatu Vatu (VUV)"},{"id":"WST","name":"Samoan Tala (WST)"},{"id":"XAF","name":"CFA Franc BEAC (FCFA)"},{"id":"XCD","name":"East Caribbean Dollar (EC$)"},{"id":"XDR","name":"Special Drawing Rights (XDR)"},{"id":"XOF","name":"CFA Franc BCEAO (CFA)"},{"id":"XPF","name":"CFP Franc (CFPF)"},{"id":"YER","name":"Yemeni Rial (YER)"},{"id":"ZAR","name":"South African Rand (ZAR)"},{"id":"ZMK","name":"Zambian Kwacha (1968-2012) (ZMK)"},{"id":"ZMW","name":"Zambian Kwacha (ZMW)"},{"id":"ZWL","name":"Zimbabwean Dollar (2009) (ZWL)"}
   ];
for(var i=0;i<currencies.length;i++){
    currencieNames.push(currencies[i]["id"]); 
} 

var shortArrays = [], i, len;
for (i = 0, len = currencieNames.length; i < len; i += 50) {
    shortArrays.push(currencieNames.slice(i, i + 50));
}

return {
    currencies: currencieNames,
    refresh: refresh(),
 };

function refresh() {
for(var i =0;i<shortArrays.length;i++){
  var url = YAHOO_FINANCE_URL_PATTERN.
  replace('PAIRS', 'USD' + shortArrays[i].join('","USD'));
   $http.jsonp(url).success(function(data) {
    if(data.query.results.rate){
     angular.forEach(data.query.results.rate, function(rate) {
         var currency = rate.id.substring(3,6);
         newUsdToForeignRates.push(rate);
         //Array with all values :- working fine
         console.log(newUsdToForeignRates);
     });
    }
   });
}
// this always null
console.log(newUsdToForeignRates);
return newUsdToForeignRates;
}

}]);

我来自控制器的电话如下

 this.inCurr = serviceobject.refresh;
 console.log(this.inCurr);
4

2 回答 2

2

调用是异步的$http,所以你需要返回一个promise,然后在数据准备好时解析promise。此外,Angular 的全局语法也不是好的做法。由于您在循环中进行 ajax 调用,因此您需要使用$q.allfor 每个 promise 并在所有 ajax 调用完成时解析主 promise(循环中的所有 promise 都完成)。这是您需要做的基本逻辑。现场演示(点击)。

var app = angular.module('myApp', []);

app.controller('myCtrl', function(refresh) {
  //refresh() then use the data
  refresh().then(function(allData) {
    //this will run when all ajax calls are done - the refresh promise is resolved
    console.log(allData);
  });
});

app.factory('refresh', function ($q, $http) {

  var arr = [
    1,2,3,4
  ];

  //I made this into a function to avoid the loop incrementing "i"
  function makeCall(def) {
    //make the ajax call
    $http.get('my-file.json').then(function(resp) {
      //resolve this call's promise with the response data
      def.resolve(resp.data);
    });
  }

  return function() {
    //make a deferred for this function
    var deferred = $q.defer();

    //store all promises in one array for $q.all to use
    var allPromises = [];
    for (var i=0; i<arr.length; ++i) {
      //make a deferred for this call
      var def = $q.defer();
      //store the promise
      allPromises[i] = def.promise;
      makeCall(def);
    }

    //wait for all promises to resolve
    $q.all(allPromises).then(function(allData) {
      //then resolve the main promise
      //when this resolves, the "then" for "refresh()" will fire in the controller
      deferred.resolve(allData);
    })

    //return the main promise
    return deferred.promise;
  };
});
于 2014-01-19T16:56:44.337 回答
1

这是因为 $http 方法(除非请求被缓存)异步工作。因此,当您到达 console.log(newUsdToForeignRates) 时,尚未返回 HTTP 调用的结果。如果您需要处理结果,您可以使用 $q.all ($q.all)来 $watch 并使用或将所有查询组合成一个 Promise

于 2014-01-19T16:47:07.873 回答