What is the proper way to reconnect to a socket using an AngularJS service?

I have encountered an issue while writing an AngularJS app. My application relies on a socket connection to retrieve data consistently, so I created a factory as shown below:

var Service = {};
var ws = new WebSocket("url");
var timer;

Service.onMessage = function(message) { /* some code */ };
Service.onClose = function() {
    timer = $interval(function () {
            ws = new WebSocket("url");
            Service.connect();
    }, 1000);
};
Service.onOpen = function() {
    console.log("open");
    if (timer) $interval.cancel(timer);
};
Service.onError = function(error) { /* some code */ };

Service.connect = function() {
        // (Re)connect

        // Reattaching handlers to object
        ws.onmessage = Service.onMessage;
        ws.onclose = Service.onClose;
        ws.onopen = Service.onOpen;
        ws.onerror = Service.onError;
}
return Service;

The problem arises when the server is down and the socket connection is lost. The onClose event triggers but I am unsure how to reconnect with the socket properly. I want to periodically check the connection status, maybe every 1 or 5 seconds. In my current implementation, I create a new socket object each time the connection is lost, resulting in multiple connections when the server comes back online. How can I modify my code to maintain only one active connection? Any suggestions would be greatly appreciated.

Answer №1

How can I successfully re-establish a connection with a socket? Is it recommended to check the connection status every few seconds?

While this question may not be directly related to Angular, here is a general JavaScript solution (not tested):

function reconnect(url){
   ws = new WebSocket(url);
}

ws.onclose = function(){
   myTimeout = setTimeout(function(){reconnect('mywsURL')}, 5000);
};

In an Angular application, you can use:

var interval = $interval(your_callback, 5000);

To cancel the timeout:

$interval.cancel(interval);

I recommend exploring the code of this interesting library.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

issue with border in hover effect on navigation menu

I'm looking to replicate a menu design similar to the one shown in this image. My main issue lies with the hover effect, specifically changing the vertical images on both sides. I've made some progress so far and you can view it here: http://jsf ...

Error encountered with $http.get during ng-click execution

edit: to make it clear, I have excluded some input fields and additional code, but all necessary information is included. I have searched extensively online without finding a solution. In my html, I am executing a function userSearch() on ng-click. The ng ...

Navigating the perplexing world of Jquery, ajax, and the enigma of the amp

After reading up on best practices, I've learned the importance of encoding any URL passed to another source. This article explains it further: I recently wanted to share the current track time of a song I was listening to. With the help of the youru ...

Angular calls a factory method from within its own factory

When working in my controller, I encountered a situation where I needed to call a factory function recursively. Previously, the code worked fine as simple JavaScript functions not defined within the factory itself, but I wanted to improve isolation. Here ...

What is the method for retrieving array values from an attribute?

I am currently developing an Angular 6 application and I need to pass and retrieve array values dynamically through attributes. Here is the code snippet I have used for this purpose: HTML: <ul class="list-unstyled" id="list" [attr.parent_id]="123"> ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

What is the process for incorporating a compiled JavaScript library into a TypeScript project?

In my Typescript project (ProjectA), I am utilizing several node packages. Additionally, I have a babel project (ProjectB) with a build configuration that supports output for multiple module definition standards such as amd, common.js, and esm. My questio ...

Oops! There was a validation error as the duration was not formatted as a number. Please make sure to provide a valid numerical value for the duration field

When attempting to update data from a MongoDB database and checking the results on Postman, an error is encountered. The error reads as follows: "Error: ValidationError: duration: Cast to Number failed for value \"NaN\" at path \"duration&bs ...

Having trouble with your GitHub Pages site displaying properly on desktop but working fine on mobile?

I am facing an issue with my GitHub pages site on a custom domain. It works perfectly fine on mobile, but when I try to access the same URL from desktop, I encounter a DNS_PROBE_FINISHED_NXDOMAIN error. Any suggestions on why this might be happening? You c ...

problem with the height of the side navigation bar

Currently, I am in the process of creating a back-end system that includes a side navigation bar positioned on the left-hand side. To accomplish this, I have opted to utilize the Bulma CSS framework and integrate it with Laravel. Although I have implemen ...

What is the proper way to utilize the "Long" type when declaring a schema in MongoDB?

Forgive my ignorance, but I am trying to achieve something like this: var mongoose = require('mongoose'); var Long = require("long"); var UserSchema = new mongoose.Schema({ id: Long(), name: String, completed: Long(), ...

ERROR: Issue with headless environment in BROWSER SYNC

Just starting out with Angular 2, I ran the npm install command on git bash and then tried to start the typescript and lite server using npm start. However, an error popped up saying [1] [BS] Couldn't open browser (if you are using BrowserSync in a he ...

What could be the reason for the selection box in my form not changing the items when togg

I'm having an issue with my form selection box code that used to work but is now not functioning properly. Could someone please help me identify where the error lies? Essentially, I have a form with the ID #main and a select box named #chart-type. Th ...

Having trouble with removing the disabled attribute from an input file submit button

Currently, I am in the process of validating the file size and extension before it gets uploaded. My code is almost functioning perfectly, but there seems to be an issue with removing the disabled attribute from the submit button when the file meets all th ...

When incorporating Request.js and Cheerio.js into Node/Express, an unexpected outcome may occur where an empty

I am currently in the process of creating a basic web scraper using Request.js and Cheerio.js within Express. My main goal at the moment is to extract the titles of various websites. Instead of scraping each website individually, I have compiled them int ...

Is there a way to insert a secured page right before accessing the dashboard?

I am trying to create a locked page that will display a message when users access the web app from a mobile device and load a mobile layout page displaying a message like mobile is not supported. I was considering using document.addEventListener('DOMC ...

Should alert boxes and loading windows be called from Controllers or Services?

As I work on developing an AngularJS (Ionic) app, I have come across many resources emphasizing the best practices in AngularJS development. One common guideline mentioned is to avoid using controllers for DOM interactions. I currently have calls to ioni ...

How can you determine if a mouseover event is triggered by a touch on a touchscreen device?

Touchscreen touches on modern browsers trigger mouseover events, sometimes causing unwanted behavior when touch and mouse actions are meant to be separate. Is there a way to differentiate between a "real" mouseover event from a moving cursor and one trigg ...

Encountering a Mongoose error during the upsert operation with findOneAndUpdate

While attempting to upsert using findOneAndUpdate, I encountered an error. ValidatedCertificates.findOneAndUpdate( //query { "course": req.body.course_name, "batch": req.body.batch_name }, { //update ...

Set Covering: Identify an array combination that intersects with all elements of a specified target array

Suppose there is an array, A, which can be sorted if that information helps. We have multiple arrays, B, C, D, etc., all sortable and potentially overlapping with array A. The objective is to identify the smallest combination of arrays B, C, D, etc., whi ...