无法将 ws 响应分配给$scope变量



当我收到ws消息时,我在设置结果时遇到问题。
我有一个控制器,当我单击某个按钮时,它会调用getStops函数。

在这个函数(getStops(中,我使用 ws 连接,当我收到消息
(在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>

问题是,您正在从 AngularJS 上下文外部更新角度$scope变量,其中 angularjs 不知道这些更改,因此更改不会反映在 UI 中。更新绑定的过程称为摘要循环系统$scope。在这种情况下,您必须手动触发此过程才能在屏幕上查看更新。

您可以通过两种方式触发此过程

  1. 通过在$scope上调用$apply方法
  2. 或者$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;
    });
    };
    

最新更新