如何将实时数据从Node.js服务器推送到AngularJS? [英] How to push live data from nodejs server to AngularJS?
问题描述
我已成功打开服务器中与外部API的Websocket连接,以获取交易所报价数据,但不确定如何将数据连续推送到客户端/AngularJS.
I have successfully opened a websocket connection in server to an external API to get exchange ticker data but not sure how to continuously push the data to client / AngularJS.
这是路由器代码:
router.get('/live-ticker', function(req, res) {
var autobahn = require('autobahn');
var wsuri = "wss://api.poloniex.com";
var connection = new autobahn.Connection({
url: wsuri,
realm: "realm1"
});
connection.onopen = function(session) {
function tickerEvent(args, kwargs) {
res.json(args);
console.log(args);
}
session.subscribe('ticker', tickerEvent);
}
connection.onclose = function() {
console.log("Websocket connection closed");
}
connection.open();
});
我想做的是让 tickerEvent
中的数据实时更新前端的控制器:
What I'm attemping to do is to have the data from tickerEvent
live update the controller in the front end:
app.controller('liveTickerController', function($scope, $http) {
$scope.ticker = [];
var request = $http.get('/live-ticker');
request.success(function(ticker) {
console.log(ticker); //only logging data once
$scope.liveTicker = ticker;
});
request.error(function(err) {
console.log('Error: ' + err);
});
});
如何将实时更新推送到客户端?
How would get live updates pushed to client?
谢谢
推荐答案
您需要定期从服务器推送数据.
you need to push data from the server periodically.
要在客户端获得这些实时更新",仅进行ajax调用是不够的,您需要实时通信.
to get these "live updates" on the client side, a plain ajax call is not enough, you need a realtime communication.
即使在这里,您也应该使用websoket,并使用 socket.io 和
You should use websoket even here, with socket.io and angular socket.io for example you can handle this communication easily
这篇关于如何将实时数据从Node.js服务器推送到AngularJS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!