javascript - 无法将 ws 响应分配给 $scope 变量
问题描述
当我收到 ws 消息时,设置结果有问题。
我有一个控制器,当我单击某个按钮时,它会调用getStops
func。
在这个 func( getStops
) 中,我使用 ws 连接,当我收到消息
(at ws.onmessage
) 时,我需要获取
tramState['stop_id']
并将其分配给$scope.current_stop
.
然后在ul
列表中,适当的li
应该变得活跃。
但它不会发生,$scope.current_stop
总是null
。
问题出在哪里?谢谢。
angular.module('tramApp').
controller('tramController', ['$scope', 'tramAPIService', function($scope, tramAPIService) {
$scope.trams = [];
$scope.stops = [];
$scope.active_tram = null;
$scope.current_stop = null;
$scope.getStops = function (tram_id) {
tramAPIService.getStops(tram_id)
.then(stops => $scope.stops = stops);
$scope.active_tram = tram_id;
const ws = new WebSocket(`ws://192.168.0.103:8080/tram_ws/?tram_id=${tram_id}`);
ws.onmessage = (message) => {
let tramState = JSON.parse(JSON.parse(message.data));
$scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null;
console.log(tramState);
};
};
tramAPIService.getTrams()
.then(trams => $scope.trams = trams);
}]);
<ul class="list-group">
<li
class="list-group-item"
ng-repeat="s in stops"
ng-class="{'active': s.stop_id === current_stop}">
{{ s.stop_id }}, {{ s.stop_name }}
</li>
</ul>
解决方案
问题是,您正在$scope
从外部 AngularJS 上下文更新角度变量,其中 angularjs 不知道这些更改,因此这些更改不会反映在 UI 中。更新绑定的过程$scope
称为摘要循环系统。在这种情况下,您必须手动触发此过程才能在屏幕上查看更新。
您可以通过两种方式触发此过程
- 通过调用
$apply
方法$scope
或者
$timeout
和$applyAsync
方法。(首选方式)ws.onmessage = (message) => { let tramState = JSON.parse(JSON.parse(message.data)); $scope.$applyAsync(function(){ $scope.current_stop = (tramState['stop_id'] !== "None") ? Number(tramState['stop_id']) : null; }); };
推荐阅读
- angularfire2 - Angular Firebase switchmap 和 authstate 代码已弃用
- javascript - JavaScript if else 条件混乱
- c++ - 从函数 C++ 返回 3 个元素
- php - Laravel 中客户和员工门户的单独身份验证
- amazon-web-services - 如何在 ec2 实例中使用来自应用程序前端的日志流并将日志直接发送到 cloudwatch/s3 存储桶?
- css - 一个元素是否有可能在保持垂直流动的同时占据整个宽度?
- colors - PyAutoGui - 检测像素颜色
- javascript - Django Rest 框架问题
- reactjs - 在接口属性中声明两种类型
- hadoop - 是否可以从 HDFS 手动删除配置单元表的分区目录而不删除分区