如果持久化模型(Server数据库)是由一个外部应用程序改变可以Angular.js自动更新一个看法? [英] Can Angular.js auto-update a view if a persistent model (server database) is changed by an external app?
问题描述
我刚开始用Angular.js熟悉,但我想的东西时,在服务器更改为构建具有获取自动更新过的实时(无刷新)为用户查看Web应用程序机端数据库。
I'm just starting to familiarize with Angular.js, but I would like to build a web app that has a view that gets auto-upated in real-time (no refresh) for the user when something changes in the server-side database.
能否角处理这个(主要)会自动给我吗?如果是这样,在什么工作的基本机制是什么?
Can Angular handle this (mostly) automatically for me? And if so, what is the basic mechanism at work?
例如,你以某种方式设置角定期为样板的变化轮询DB?或者使用某种彗星般的机制来通知角客户端code。该模型已经改变?
For example, do you somehow setup Angular to poll the DB regularly for "model" changes? Or use some sort of Comet-like mechanism to notify Angular client-side code that the model has changed?
在我的申请中,挑战是,其他(非Web)的服务器端软件将被更新,有时该数据库。但这个问题同样适用于纯Web的应用程序,你可能有多个客户不断变化的角度,通过网络客户端数据库,他们每个人都需要在他们其中一人更改为DB(模型)。
In my application, the challenge is that other (non-web) server-side software will be updating the database at times. But this question applies equally to pure web-apps where you might have multiple clients changing the database through Angular web clients, and they each need to be updated when one of them makes a change to the DB (model).
推荐答案
您有几个选择...
-
您可以做投票通过每隔X毫秒
$超时
和$ HTTP
,或者如果数据你使用的是迷上了REST服务,您可以使用$资源
而不是$ HTTP
。
You could do polling every X milliseconds using
$timeout
and$http
, or if the data you're using is hooked up to a REST service, you could use$resource
instead of$http
.
您可以创建一个使用了一些WebSocket的实施和使用范围的服务。$适用
来处理由插座推变化。
下面是使用socket.io一个例子,一个Node.js的WebSocket的库:
You could create a service that uses some Websocket implementation and uses scope.$apply
to handle changes that are pushed by the socket.
Here's an example using socket.io, a node.js websocket library:
myApp.factory('Socket', function($rootScope) {
var socket = io.connect('http://localhost:3000');
//Override socket.on to $apply the changes to angular
return {
on: function(eventName, fn) {
socket.on(eventName, function(data) {
$rootScope.$apply(function() {
fn(data);
});
});
},
emit: socket.emit
};
})
function MyCtrl($scope, Socket) {
Socket.on('content:changed', function(data) {
$scope.data = data;
});
$scope.submitContent = function() {
socket.emit('content:changed', $scope.data);
};
}
您可以得到真正的高科技和创造的WebSocket实现同步它与服务器的角度模式。当客户端改变的东西,这种变化被自动发送到服务器。或者如果服务器的变化,它被发送到客户端。结果
下面是在旧版本的角度,再次使用socket.io的例子:<一href=\"https://github.com/mhevery/angular-node-socketio\">https://github.com/mhevery/angular-node-socketio
修改:对于#3,我一直在使用火力地堡来做到这一点。
EDIT: For #3, I've been using Firebase to do this.
这篇关于如果持久化模型(Server数据库)是由一个外部应用程序改变可以Angular.js自动更新一个看法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!