首页 > 解决方案 > 无法将 ws 响应分配给 $scope 变量

问题描述

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

在这个 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>

标签: javascriptangularjs

解决方案


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

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

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

推荐阅读