我正在尝试从 websocket 获取数据以自动更新 Controller 范围内的值。
我的服务:
mimosaApp.service("Device", function ($websocket) {
var self = this;
var ws = $websocket.$new({
url: "ws://" + window.location.host + ":81",
//mock: true,
reconnect: true
});
this.data = {};
ws.$on("$open", function() {
ws.$emit("get", "device");
});
ws.$on("$message", function (message) {
console.log("WS Received", message);
for(var key in message) {
self.data[key] = message[key];
}
console.log(self.data); // At this point, self.data contains the proper data.
});
this.send = function (obj) {
ws.$emit("set", obj);
};
});
还有我的简单 Controller :
angular.module("MimosaApp").controller("PageController", ["Device", "$scope", "$http", function(Device, $scope, $http) {
$scope.device = Device;
}]);
建立套接字连接后,浏览器会发送一条请求数据的消息($open 事件)。收到响应后,它会使用 JSON 对象更新 Device.data 对象。
但我没有看到这反射(reflect)在我的 Controller 范围/ View 中。如果在 Controller 内部,我设置类似 Device.data.name ='blah';
我可以在 Controller 范围/ View 中看到名称属性。
我是 Angular 的新手,如果我的问题不太合理,我深表歉意。 :)
我的观点是尝试像这样使用它:
<div class="container-fluid">
location
<ul>
<li ng-repeat="(key, value) in device.data">
{{key}}: {{ value }}
</li>
</ul>
<p>{{device.data.face}}</p>
</div>
最佳答案
查看 source它似乎没有在 $on
处理程序中使用 scope.$apply
调用摘要循环。这意味着 Angular 不知道对其 View 绑定(bind)的任何更新,因此 View 中不会反射(reflect)任何更改。因此,您需要在服务中手动执行此操作,您可以注入(inject) $rootScope
或仅注入(inject) $timeout
来触发摘要周期。
例子:-
注入(inject) $timeout
ws.$on("$message", function (message) {
console.log("WS Received", message);
for(var key in message) {
self.data[key] = message[key];
}
console.log(self.data); // At this point, self.data contains the proper data.
$timeout(angular.noop); //<-- just invoke a dummy digest
});
注入(inject)$rootScope
ws.$on("$message", function (message) {
console.log("WS Received", message);
for(var key in message) {
self.data[key] = message[key];
}
console.log(self.data); // At this point, self.data contains the proper data.
$rootScope.$apply(); //invoke digest
});
甚至可以使用 $q
在您的服务中创建一个虚拟 promise 。
mimosaApp.service("Device", function ($websocket, $q) {
var self = this;
var _dummyPromise = $q.when(); //<-- here
var ws = $websocket.$new({
url: "ws://" + window.location.host + ":81",
//mock: true,
reconnect: true
});
//...
ws.$on("$message", function (message) {
console.log("WS Received", message);
for(var key in message) {
self.data[key] = message[key];
}
_dummyPromise.then(angular.noop); //<-- here
});
this.send = function (obj) {
ws.$emit("set", obj);
};
});
关于javascript - Angular 中的 WebSocket 服务更新范围(使用 ngWebSocket)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30337839/