Websocket onmessage event triggered just one time

I have implemented a basic WebSocket client in an Angular 6 application.

Everything seems to be working fine, except for the fact that both socket.onmessage and

socket.addEventListener('message'
are only triggered once. There are no errors in the console, and the correct message is being received by the client (verified through websocket connection frames in the browser console). All other events work as expected.

Below is my WebsocketService class:

export class WebsocketService implements OnDestroy {
  socket: WebSocket;

  constructor(@Inject(APP_CONFIG) private config: IAppConfig, private authService: AuthService) { }

  initConnection(): void {
    this.socket = new WebSocket(
      this.config.apiEndpoint.replace(/^https?:\/\//i, 'ws://') + 'ws/');
    this.watchEvent(WSEvent.ERROR).subscribe(data => {
      console.log(data);
    });
  }

  watchEvent(wsevent: WSEvent): Observable<any> {
    return new Observable(observer => {
      this.socket.addEventListener(wsevent, function(event) {
        observer.next(event);
      });
    });
  }

  onMessage(): Observable<any> {
    return new Observable(observer => {
      this.socket.onmessage = function(event) {
        observer.next(event);
      };
    });
  }

  ngOnDestroy() {
    // this.socket.close();
  }
}

wsevent:

export enum WSEvent {
  CLOSE = 'close',
  OPEN = 'open',
  MESSAGE = 'message',
  ERROR = 'error'
}

usage:

this.wsService.watchEvent('message').subscribe((data) => {
   console.log(data);
});


this.wsService.onMessage().subscribe((data) => {
  console.log(data);
});

Upon testing, I noticed that both console.log(data); statements only display the first message sent to the client, regardless of how many times or what content is sent - the onmessage event is triggered only once.

Update: I have updated this post with a solution that actually works. The issue was due to calling observer.complete(); immediately after observer.next(event);, which prematurely ended the stream.

Answer №1

Eliminated the usage of observer.complete(); within the watchers.

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

The issue with NGX-Bootstrap/Angular Pagination arises when attempting to adjust the maxSize input while the screen view (width) is being altered

Currently, I am utilizing the Pagination component from Valor Software (click here to access). I am interested in adjusting the maxSize input dynamically based on changes in screen width. For reference, please see this example: Click to view example. It ...

What does the "start" script do in the package.json file for Angular 2 when running "concurrent "npm run tsc:w" "npm run lite"" command?

What is the purpose of concurrent in this code snippet? "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "Concurrent npm run tsc:w npm run lite" } ...

What is the best way to automatically log out a user when a different user logs in on the same browser?

Currently, I am encountering an issue where there are two separate dashboards for different types of users - one for admin and the other for a merchant. The problem arises when an admin logs in on one tab and then a merchant logs in on another tab in the s ...

` `angular2 get the element reference of a component that is not a direct descendant` `

Within my application, the structure is as follows: <fin-header></fin-header> <main></main> <fin-footer></fin-footer> I would like to implement scrolling within the header to a specific component within main. However, ...

Assets failing to duplicate during ng build in production

Currently, I'm developing an application using Angular 4. I recently added a new SVG image to the assets/images folder and made the necessary changes in the angular-cli.json file as well. When I run 'ng build' locally, it successfully copies ...

Discovering the category for ethereum, provider, and contract

My current interface looks like this: interface IWeb3 { ethereum?: MetaMaskInpageProvider; provider?: any; contract?: any; }; I was able to locate the type for ethereum using import { MetaMaskInpageProvider } from "@metamask/providers", ...

Error: The method that was custom created is not functioning as expected

I am working on a project where I have a collection of hero buttons that come with a customized animation which is defined in the button.component.ts file. These buttons start off as inactive, but when one is clicked, it should become active. To achieve th ...

The interface 'Response<ResBody>' has been incorrectly extended by the interface 'Response'

I am currently working with typescript and express in a node.js environment. Whenever I compile my code, I encounter the following bug: node_modules/@types/express-serve-static-core/index.d.ts:505:18 - error TS2430: Interface 'Response<ResBody>& ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

Issue with Angular application failing to fetch data from JSON server

I've been attempting to retrieve data from a local server, but so far I'm not getting any results. The concept is to have a service handle the retrieval process and return an observable for any components in need of the data to subscribe to. dis ...

Angular6 : PrimeNg datatable: the nova-light theme failing to activate

I'm currently working on an Angular 6 app that is equipped with the latest version of PrimeNG (6.1.4) and I am using a simple datatable component. My goal is to apply the nova-light theme to my datatable, but unfortunately, it is not being applied cor ...

Is there a way to simultaneously filter by two attributes using mat-select-filter in Angular?

I have integrated the mat-select-filter library in my Angular project, but I am facing an issue with the displayMember filter. Currently, it only filters by code, but I would like it to also filter by name simultaneously. Is there a way to achieve this u ...

What is the process for defining the root of a project in ESLint?

I've been working on a project using Next.js and Typescript. My imports look like this: import Component from "/components/Component/Component";, with the root directory being specified as /src. This setup works fine in Next.js, but ESLint k ...

Tips on including a trash can symbol to rows in a bootstrap table using React

I am working on a table that contains various fields, and I want to add a trash icon to each row so that when it is clicked, the specific row is deleted. However, I am encountering an issue where the trash icon is not showing up on the row and I am unable ...

The push() method replaces the last item in an array with another item

Two objects are available: ej= { name="", code: "", namebusinessG:"", codebusinessG:"" }; group = { name:"", code:"" } Both of these objects will be stored in two arrays: groupList:any[]=[]; ejList:any[]=[]; The program flow s ...

NPM IP library susceptible to Server-Side Request Forgery (SSRF) vulnerabilities

Received Security Alert from GitHub's Dependabot Regarding an Issue in My Angular Repository A security vulnerability has been identified in all versions of the NPM package "ip," allowing a malicious actor to execute arbitrary code and access sensiti ...

Angular removing every query string parameters

Linked to but distinct from: How to maintain query string parameters in URL when accessing a route of an Angular 2 app? I am facing an issue with my basic Angular application where adding a query parameter results in its removal, both from the browser&apo ...

When running `ng serve` or `ng build --prod`, the dist folder is not created in an Angular 4 application

I recently completed building an Angular 4 app using angular-cli version 1.0.4 and generated the production build with the command ng build --prod. However, I encountered a problem as the expected dist folder was not created after executing this command. ...

Conceal the toolbar element if it is not at the top of the page

I am encountering an issue with my toolbar. When I scroll down, the transparent background of the toolbar disappears and it looks like this: . How can I hide this component when the page is scrolled down and show it again when scrolling back up to the top ...

SVG is not incorporated in the Typescript build

I'm facing an issue where my build using tsc --project tsconfig.dist.json (refer to the file below) does not include the assets (.svg files) that are imported and used in the code. How can I make TypeScript include these assets in the build? Some con ...