There is no value stored in the Angular BehaviorSubject

My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code:

export class WebSocketConnectionService {

  public ResponseList: BehaviorSubject<WebSocketResponse> = new BehaviorSubject(null);

  private socket: any;

  private webAuth: Auth;

  private pingInterval: any;

  constructor(private authService: AuthService) {
    this.authService.UserToken.subscribe(myToken => {
      const myUUID = this.authService.getUUID();
      this.webAuth = {token: myToken, uuid: myUUID};
      console.log('Auth: ', this.webAuth);
    });
    this.ResponseList.subscribe(response => {
      console.log('New Response in List: ', response);
    })

    this.socket = new WebSocket(environment.socket_url);
    this.socket.onmessage = this.onMessage;
    console.log('Socket: ', this.socket);

   }


   private onMessage(message: MessageEvent) {
     const body: WebSocketResponse = JSON.parse(message.data);
     console.log('Message: ', message);
     console.log('data: ', body);
     console.log('list: ', this.ResponseList);
     this.ResponseList.next(body);
   }

  public sendConnection(user: UserItem): Promise<any> {
    return new Promise((resolve, reject) => {

      try {
        this.sendInternalCommand('link_user', user);
        resolve();
      } catch(e) {
        console.error(e);
        reject();
      }
    })
  }


  private sendInternalCommand(command: string, data: any) {
    const message: WebSocketConnectionItem = {
      version: 1,
      event: command,
      auth: this.webAuth,
      body: data
    };
    const string_message = JSON.stringify(message);
    console.log('Send: ', string_message);
    this.socket.send(string_message);
  }
}

I managed to successfully send the open ConnectionItem. However, I encountered an issue in onMessage where the object ResponseList turns out to be null.

What could possibly be the problem here?

Your assistance will be greatly appreciated.

Answer №1

It seems like the issue lies in this particular line of code:

this.socket.onmessage = this.onMessage;

The socket is invoking the onmessage function within its own context, making 'this' refer to the WebSocket instance. To resolve this, you can try binding the onMessage method to an instance of the WebSocketConnectionService class:

this.socket.onmessage = this.onMessage.bind(this);

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

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

How to detach functions in JavaScript while preserving their context?

Can functions in JavaScript be detached while still retaining access to their context? For instance, let's say we have an instance of ViewportScroller called vc. We can retrieve the current scroll position with the following method: vc.getScrollPosi ...

Unable to find module 'child_process'

Here is the content of my main.ts file: import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { environment } from './environments/environment'; if ...

Using React to iterate through the child components of the parent

I have created a component that can accept either a single child or multiple children. Here is an example with multiple children: <SideDataGridItem> <div id='top'> <div>A1</div> <div>B1</div> ...

Using Angular with Web API to transmit FormFile data from client to API

I am facing a challenge with creating an object (referred to as a "Ticket") along with 0-n children (known as "Attachments") in my Angular application and sending this information to my dotnet core Web API. However, this is more of a logical inquiry that I ...

Is there a way to verify the presence of multiple array indices in React with TypeScript?

const checkInstruction = (index) => { if(inputData.info[index].instruction){ return ( <Text ref={instructionContainerRef} dangerouslySetInnerHTML={{ __html: replaceTextLinks(inputData.info[index].instruction) ...

Encountering difficulties resolving the dependency tree for an angular-ionic project

Node version: v16.3.0 ng version: 12.1.0 Currently working on an Angular-Ionic 5 project Encountered an error while running the npm install command 2. Also tried running npm install --force but faced a different error ...

conceal the selected button upon moving to a different page

Whenever I click on the details button, it directs me to the details.html file. However, when navigating to another page, the details button still appears and I want to hide it in such cases. <button mat-button (click)="onSelectApp(app)"><mat-ic ...

Guide to customizing CSS styles within a div element using TypeScript code in a Leaflet legend

I'm struggling to add a legend to my map using Angular 5 and typescript. I need help with setting CSS styles for the values (grades) that are displayed on the legend. Can someone guide me on where to put the styles? TS: createLegend() { let lege ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

What is the solution for resolving the error message "Property '' does not exist on type 'typeof import'"?

Hi everyone, I'm a new Angular developer who is working on implementing authentication. I recently added the auth0-angular package to my project and now I'm encountering an error when creating a WebAuth() instance in my code editor (VS Code). Th ...

Angular: Reveal or conceal targeted rows on click interaction

I have a scenario where I am displaying data in a table with multiple rows. Each row has its own set of data and a button that triggers a function when clicked. <table> <th>Col-1</th> <th>Col-2</th> <th>< ...

Preventing angular router events from being logged in the console

In the process of developing an angular application, I have encountered a challenge with the {RouterModule} from @angular/router. Although I rely on console.log to troubleshoot my app, the router module has unleashed a flurry of router events in the conso ...

One question I have is how I can successfully send a value within the RxJS subscribe function

I am currently in the process of transitioning the code to rxjs Here is my original code snippet. userAuth$: BehaviorSubject<ArticleInfoRes>; async loadArticleList(articleId: number) { try { const data = await this.articleApi.loadArticl ...

What are the best methods for repairing a malfunctioning Drawer?

My template can be found here: SANDBOX When transitioning to a nested route, I am experiencing a double rendering issue which causes the DRAWER to reopen. How can this be fixed? You can observe this effect in the "NESTED" tab. It is important that the fi ...

Unable to fulfill the return type requirement in a typed TypeScript function

In this scenario, let's consider the following type: export type Transformer = <T extends any[], U>( data: T, ) => U; Now, let's examine a function that needs to adhere to this type: export const transform: Transformer = ( d ...

Releasing Typescript 2.3 Modules on NPM for Integration with Angular 4

Although there are instructions available in Writing NPM modules in Typescript, they are outdated and there are numerous conflicting answers that may not be suitable for Angular. Additionally, Jason Aden has delivered an informative presentation on youtu ...

Setting a property with a generic type array: Tips and tricks

Currently, I am working on implementing a select component that can accept an array of any type. However, I am facing some challenges in defining the generic and where to specify it. My project involves using <script setup> with TypeScript. Here is ...

Unfortunately, the package "error-ex" could not be found when attempting to access it through the npm registry

I am encountering an issue while trying to install npm package dependencies in my Angular application. The error message I receive is related to "error-ex@^1.2.0". Can anyone provide guidance on how to resolve this problem? npm ERR! code E404 npm ERR! 404 ...