I'm facing an issue with setting the result when receiving a websocket message.
I have a controller that, upon clicking a button, triggers the getStops
function.
Within this function (getStops
), I utilize a websocket connection to receive messages
(at ws.onmessage
), where I need to extract
tramState['stop_id']
and assign it to $scope.current_stop
.
Subsequently, the corresponding li
in the ul
list should become active.
However, this is not happening as expected; $scope.current_stop
always remains null
.
Any insights on where the problem might be originating from? Appreciate any help.
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>