Search code examples
javascriptangulartypescriptangular-services

Angular 9 service variable changes to undefined after function call, within the same file


I have a interface defined as so:

export interface Action {
    (...args: any[]): void;
}

A service defined as so:

import { uuid } from 'uuidv4';
import { Action } from '../interfaces/action';
import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root',
})
export class SocketService {
    private onMessage: Action[] = [];
    private socket: WebSocket = null;

    constructor() {
        this.socket = new WebSocket('ws://localhost:8080/1234');

        this.socket.onopen = this.OnOpen;
        this.socket.onmessage = this.OnMessage;
    }

    private OnMessage(message) {
        let json = JSON.parse(message.data);

        console.log(this.onMessage);
        if (this.onMessage) {
            this.onMessage.map((x) => x(json));
        }
        console.log(json);
    }

    public set OnMessageActions(action: Action) {
        console.log(this.onMessage);
        this.onMessage.push(action);
        console.log(this.onMessage);
    }

    private OnOpen() {
        console.log(this.onMessage);
        console.log('Connection opened');
        console.log(this.onMessage);
    }
}

then finally a component defined as such:

import { Component, OnInit } from '@angular/core';
import { SocketService } from '../../services/socket.service';

@Component({
    selector: 'app-chat',
    templateUrl: './chat.component.html',
    styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
    messages: Object[] = [];

    public get ReadyState(): number {
        return this.socketService.Socket().readyState;
    }

    constructor(private socketService: SocketService) {}

    ngOnInit(): void {
        if (!this.socketService.Socket()) {
            return;
        }

        this.socketService.OnMessageActions = this.OnMessage;
    }

    OnMessage(message: any) {
        switch (message.type) {
            case 'history':
                this.messages = message.data;
                break;
        }
    }
}

When the setter function is called, the first console log displays an empty array, which is expected, the push happens and the second console log displays an array with 1 item. Again, expected.

The issue is, when the OnOpen and OnMessage functions are called the array is undefined.

The logic behind the Actions interface is something that I was attmepting to mirror from C#'s/Unity's actions.


Solution

  • Because this context in your function OnOpen does not refer to SocketService instance

    Let try rewrite your OnOpen function like this

    OnOpen = () => {
         const _this = this
         console.log(_this.onMessage)
    }