我通过套接字连接从后端获得更新。我希望使用AngularJS自动更新Frontend,同时使用数据对象来获取从后端获得的数据。
我有什么?
模板:
Status: {{unit.getStatus()}}
控制器1:
function ($scope, unitFactory) {
// register to unit factory to get the updates and do
// $scope.unit = data.getUnit();
}
控制器2:
function ($scope, unitFactory) {
// register to unit factory to get the updates and do
// $scope.unit = data.getUnit();
// $scope.foo = data.getFoo();
}
服务:
function(requestFactory) {
var unit = {},
foo = {};
Sockets.socket('unit', function (response) {
unit = new Unit(response['data']);
foo = new Foo(response['foo']);
// This is the data object which has to be send to the controllers
var Data = {
getUnit: function () {
return unit;
},
getFoo: function() {
return foo;
}
// some more functions...
}
});
}
套接字:
channel.on('data', function (event) {
try {
event = JSON.parse(event);
// successCallback is what is given as second parameter in the `Service`.
$rootScope.$apply(successCallback(event));
} catch (e) {
console.log('Error: ' + e);
}
});
它应该如何协同工作?
Sockets
对象Sockets
调用Service
Service
中的回调函数处理数据任何人都可以帮助我使用 MISSING 部分吗?我尝试了很多不同的方法,但每次都跑到死路。
答案 0 :(得分:0)
您是否尝试过返回数据的承诺,然后是$ state.reload()?
答案 1 :(得分:0)
使用'数据模型模式'解决了问题:
模板1(由控制器1使用):
Status: {{unit.data.getStatus()}}
模板2(由Controller 2使用):
Status: {{foo.data.getBar()}}
控制器1:
function ($scope, unitFactory) {
$scope.unit = unitFactory.getUnit();
}
控制器2:
function ($scope, unitFactory) {
$scope.unit = unitFactory.getUnit();
$scope.foo = unitFactory.getFoo();
}
服务:
function(requestFactory) {
var unit = { data:{} },
foo = { data:{} };
Sockets.socket('unit', function (response) {
unit.data = new Unit(response['data']);
foo.data = new Foo(response['foo']);
});
return
getUnit: function ()
return unit;
},
getFoo: function() {
return foo;
}
// some more functions...
}
}
套接字:
channel.on('data', function (event) {
try {
event = JSON.parse(event);
// successCallback is what is given as second parameter in the `Service`.
$rootScope.$apply(successCallback(event));
} catch (e) {
console.log('Error: ' + e);
}
});
由于数据存储在对象中,因此模板中的数据会更新(因为它是参考)。我必须习惯这些额外的属性data
并且它看起来不太好但它确实起作用。