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

Bootstrap Modal Fails to Display Image Within Its Container

I'm currently working on my e-commerce website, where I'm attempting to implement a feature that allows users to view product images in a modal for a closer look. The product page contains a list of images, and when a user clicks on one, it shoul ...

Learn how to configure gulp-typescript to automatically generate individual JavaScript files for each TypeScript file within the same directory

My interest lies in utilizing the gulp-typescript module for handling typescript compilation. My goal is to set up a configuration where each typescript file translates into one javascript file in the corresponding directory, similar to how it works with t ...

Event triggered by clicking on certain coordinates

Just starting with @asymmetrik/ngx-leaflet and Angular, so this might be a beginner's issue... I'm working on an Angular.io (v5) project that incorporates the @asymmetrik/ngx-leaflet-tutorial-ngcli Currently, I'm trying to retrieve the coo ...

Issue with integrating Bootstrap into Angular 2

When attempting to link to the bootstrap.css file located in the node_modules folder within index.html, I encountered an error. The application's folder structure is as follows: ecommerce-app/node_modules ecommerce-app/src/app/index.html All attem ...

Error in Compiling HTML Elements Collection<<Element>

Currently, I am developing an eCommerce application that features a popup window for users when they click on "Add to Cart." This popup allows users to select product variations and quantities before adding the item to their cart. The popup consists of a s ...

Issue detected in the console: Angular and Express code linked with status code 200 displaying an error

I am attempting to delete data along with an image connected to that data via an image Id using a get route (since the delete route didn't work out for me). The data is successfully being deleted, but I keep receiving a 200 OK response followed by an ...

Share the component with css and font via npm

I am looking to release an angular 2 component on NPM. This particular component utilizes CSS that references certain fonts. I have figured out how to publish the .ts files, but I am unsure about how to handle the CSS and font files. Here is what I curren ...

Methods for transforming a TypeScript class instance containing getter/setter properties into a JSON format for storage within a MySQL database

I am currently working on a TypeScript class that includes a getter and setter method: export class KitSection { uid: string; order: number; set layout(layout: KitLayout) { this._layout = new KitLayout(layout); } get layout( ...

Unable to access the suggestion list within the modal

I incorporate the PrimeNG AutoComplete feature within a PrimeNG Dialog, displaying a list of elements below the AutoComplete in the dialog. My objectives are: To set the max-height of the modal dialog to 300, and have a visible scrollbar if the total ...

TypeScript's type casting will fail if one mandatory interface property is missing while an additional property is present

While running tsc locally on an example file named example.ts, I encountered some unexpected behavior. In particular, when I created the object onePropMissing and omitted the property c which is not optional according to the interface definition, I did not ...

Merging Type-GraphQL and Typegoose through a Variety of Decorators

Using a combination of Type-GraphQl and Typegoose, I aim to streamline my data definitions by consolidating them into one source for both GraphQL schemas and Mongoose queries. Is it feasible to merge the two libraries in a way that allows me to describe bo ...

Use RxJS to ensure one observable waits for another observable to emit a non-null value

I am currently facing an issue with my setter function in TypeScript. In this setter, I assign a class member observable called systemAreasOptions$. The reason behind doing this in the setter is because it needs to wait for the observable mappedItem$ to ...

Having trouble utilizing HTML Canvas in the newest release of Angular and TypeScript

After extensive searching on the internet, I have not been able to find any working examples of using HTML canvas in Angular. It seems that changes in syntax in Typescript and Angular's newer versions have rendered all existing solutions obsolete. I ...

Unable to find solutions for all parameters in the Application Module: (?). Error occurred at syntaxError (compiler.js:1021) on the site stackoverflow.com

Upon reverting my Angular project from version 7 to 6 and integrating Angular Universal using @ngToolkit, a specific error message appeared in the browser console: The parameters for Application Module cannot be resolved: (?). at syntaxError (compiler.js: ...

What is the correct way to access and assign a value from a different getter or setter? I am facing an issue with the creation of my second array

Two http GET API calls are being made in the constructor. The first call is working fine and has a getter/setter to filter the main array (studentNameData) into a filtered array (filteredName). However, the second call is also trying to do the same thing b ...

Obtaining an URL with parameters from a server using Angular 6

I am working on retrieving a URL from the Java backend in my Angular application. I need to specify the folder number in the URL to fetch a list from that specific folder. What format should I use and how can I make it dynamic to accept any folder number, ...

The "ngx-places" directive does not have an "exportAs" setting

I recently added the ngx-google-places-autocomplete module to my project. However, upon configuring it, I encountered the following error: core.js:14597 ERROR Error: Uncaught (in promise): Error: Template parse errors: There is no directive with "expo ...

Is it possible for Typescript to automatically determine the exact sub-type of a tagged union by looking at a specific tag value?

I have an instance of type Foo, which contains a property bar: Bar. The structure of the Bar is as follows: type ABar = {name: 'A', aData: string}; type BBar = {name: 'B', bData: string}; type Bar = ABar | BBar; type BarName = Bar[&apos ...

Build a Node.js application using TypeScript and all necessary dependencies

I've developed a Node.js application using TypeScript and now I'm looking to compile it. Currently, only the source files in the src folder are included in the build. However, I also want to incorporate dependencies such as express, body-parser, ...

Using the Amazon Resource Name (ARN) of a Cloud Development Kit (CDK) resource in a different

Having trouble obtaining the ARN of my AWS CDK stack's Step Functions state machine for my lambda function. The ARN is constantly changing and I'm unsure how to access it. I attempted to create a .env file alongside the lambda function's in ...