Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
56
rated 0 times [  61] [ 5]  / answers: 1 / hits: 28043  / 10 Years ago, thu, april 3, 2014, 12:00:00

In my AngularJS app I have a service that is based on WebSocket. If the WebSocket connection breaks, I want to fully 'restart' the application (go to default page from $route, recreate the service etc.). Is that achievable? This is how I started, but from that point I have no idea how to proceed:



Module:



(function () {
angular.module('mainModule', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/home', {

templateUrl: 'partials/home.html',
controller: 'appController'
}).
when('/register', {

templateUrl: 'partials/register.html',
controller: 'appController'
}).
otherwise({
redirectTo: '/home'
});
}]);
}());


Service:



(function () {

var app = angular.module('mainModule');

app.service('$wsService', ['$q', '$window', function ($q, $window) {

$window.console.log(WebSocket SERVICE: started);

var self = this;
var ws = new WebSocket(ws://127.0.0.1:9090);
this.isConnected = function (m) {};

ws.onopen = function () {
$window.console.log(WebSocket SERVICE: connected);
self.isConnected(true);
};

ws.onmessage = function (m) {
//do whatever I want to do
};

ws.onerror = function () {
$window.console.log(WebSocket SERVICE: disconnected);
self.isConnected(false);
};

}]);
}());


Controller:



(function () {

var app = angular.module('mainModule');

app.controller('appController', ['$route', '$scope', '$wsService', function ($route, $scope, $wsService) {

$wsService.isConnected = function (m) {
//restart logic
};
}]);
}());


So as my 'restart logic' I tried $route.reload(); but as you already know it doesn't do what I need. Eventually I will have a warning message pop up (bootstrap modal) informing the user that the connection has been lost, and on a button click in that modal it will reload the app and go to /home. I am not asking how to do that popup etc as this is already done. As for now however, I need to figure out just the logic for total reload of the app. Any ideas? Thanks.


More From » angularjs

 Answers
4

To answer my own question, achieved with a trial and error:



$scope.$apply(function() {
$location.path('/home');
$window.location.reload();
});


This will go to /home (default) and reload everything, thus creating new service, module, controllers etc. If there is a better way of doing it (if I change default path to /blah in my module, this won't pick it up and thus I will have to edit this code too), let me know :)


[#71635] Wednesday, April 2, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
iliana

Total Points: 246
Total Questions: 109
Total Answers: 82

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;