4

我正在尝试从 yahoo 的 api 获取股票报价,并且正在使用 angular 的 $http.jsonp 方法。目标是当结果返回时,让应用程序转到这条路线:'/stocks/show_stock'。我试图以两种方式做到这一点,但都不起作用 1)我发表声明:

window.location = '/stocks/show_stock'

在包装 JSONP 响应的回调函数中 2)我把语句:

$location.path '/stocks/show_stock'

在 HTTPpromise 回调中。(见代码中的注释)

这是我的代码(在咖啡脚本中):

#THIS IS THE CALLBACK FUNCTION THAT I SEND WITH THE JSONP REQUEST  
window.stock_quote_callback = (data)->
  console.log data #THIS WORKS AND I CAN SEE THE DATA RETURNED FROM YAHOO
  window.stock_quote_result = data.results
  alert 'I am in the callback'
  #THE STATEMENT BELOW DOES NOT WORK EVEN THOUGH I CAN SEE THE ALERT ABOVE
  window.location = '/stocks/show_stock'

angular.module('Services').service 'StockSupplier', ($http)->
  get_stock = (symbol)->
    q = 'select * from yahoo.finance.quotes 
        where symbol in ("'+symbol+'")
        &format=json&
        diagnostics=true&
        env=http://datatables.org/alltables.env&
        callback=stock_quote_callback'
    url = 'http://query.yahooapis.com/v1/public/yql?q='+q 
    $http.jsonp(url).then (data)->
      #THE CODE BELOW NEVER EXECUTES EVEN THOUGH RESULT IS RETURNED
      alert 'This should pop up when result returns'
      $location.path'/stocks/show_stock'

  {
    get_stock: (symbol)-> get_stock(symbol)
  }

先感谢您。

4

1 回答 1

1

我不写coffeescript,所以我把它翻译成javascript。你忘了注入$location服务,除了我刚刚替换了callback=stock_quote_callbacktocallback=JSON_CALLBACK并创建了一个运行良好的 plunker:http ://run.plnkr.co/hCAdohIJIr9Odn3m/ (来源:http ://plnkr.co/edit/a7C6k0QVoXnaTyImSUkb ?p=预览)。

angular.module('Services').service('StockSupplier', function($http,$location) {
  var get_stock;
  get_stock = function(symbol) {
    var q, url;
    q = 'select * from yahoo.finance.quotes where symbol in ("' + symbol + '")&'+
        'format=json&'+
        'diagnostics=true&'+
        'env=http://datatables.org/alltables.env&'+
        'callback=JSON_CALLBACK ';
    url = 'http://query.yahooapis.com/v1/public/yql?q=' + q;
    return $http.jsonp(url).then(function(data) {
      alert('This should pop up when result returns');
      $location.path( '/stocks/show_stock' );
    });
  };
  return {
    get_stock: function(symbol) {
      return get_stock(symbol);
    }
  };
});
于 2013-05-25T18:40:20.160 回答