如果外部应用程序更改了持久模型(服务器数据库),AngularJS可以自动更新视图吗? [英] Can AngularJS auto-update a view if a persistent model (server database) is changed by an external app?
问题描述
我刚刚开始熟悉AngularJS,但是我想构建一个Web应用程序,当服务器端发生变化时,该应用程序的视图可以为用户实时自动升级(无刷新)数据库。
I'm just starting to familiarize with AngularJS, 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.
AngularJS可以自动处理这个(大部分)吗?如果是这样,工作中的基本机制是什么?
Can AngularJS handle this (mostly) automatically for me? And if so, what is the basic mechanism at work?
例如,您是否以某种方式设置AngularJS以定期轮询数据库以进行模型更改?或者使用某种类似Comet的机制来通知AngularJS客户端代码模型已更改?
For example, do you somehow setup AngularJS to poll the DB regularly for "model" changes? Or use some sort of Comet-like mechanism to notify AngularJS client-side code that the model has changed?
在我的应用程序中,挑战是其他(非Web) )服务器端软件有时会更新数据库。但是这个问题同样适用于纯web应用程序,您可能有多个客户端通过AngularJS 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 AngularJS web clients, and they each need to be updated when one of them makes a change to the DB (model).
推荐答案
您有几个选择......
You have a few choices...
-
你可以使用
$ timeout
和$ http
每隔X毫秒进行一次轮询,或者你是否有数据使用连接到REST服务,您可以使用$ resource
而不是$ 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实现的服务,并使用 scope。$ apply
来处理由插座。
这是一个使用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实现与服务器的Angular模型。当客户端更改某些内容时,该更改会自动发送到服务器。或者如果服务器发生变化,它会被发送到客户端。
这是旧版Angular中的一个例子,再次使用socket.io:https://github.com/mhevery/angular-node-socketio
编辑:对于#3,我一直在使用 Firebase 来执行此操作。
EDIT: For #3, I've been using Firebase to do this.
这篇关于如果外部应用程序更改了持久模型(服务器数据库),AngularJS可以自动更新视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!