Updating views in Angular 2 based on changes in component properties

I recently set up a WebSocket service and component, but I'm facing challenges with updating the view when new data is received through the WebSocket connection.

websocket.service.ts

import {Injectable} from "angular2/core";
import {Observable} from 'rxjs/Observable';

@Injectable()
export class WebsocketService {

    observable: Observable;
    websocket = new WebSocket('ws://angular.local:8080');

    constructor() {
        this.observable = Observable.create(observer =>
            this.websocket.onmessage = (msg) => observer.next(msg);
            this.websocket.onopen = (msg) => console.log('connection opened');
        );
    }
}

runner.component.ts

import {Component} from "angular2/core";
import {WebsocketService} from "./websocket.service";

@Component({
    selector: "runners-list",
    templateUrl: "../partials/runners-list.html",
    providers: [WebsocketService],
    styleUrls: ["../css/app.css"]
})

export class RunnerComponent {

    output: any;

    constructor(private _websocketService: WebsocketService) {
        _websocketService.observable.subscribe(
            function onNext(data) {
                this.output = data;
                console.log(this.output);
            },
            function onError(error) {
                console.log(error);
            },
            function onCompleted() {
                console.log('subscription completed');
        });
    }
}

runners-list.html

<h1>{{output}}</h1>

Although the onNext method in the component successfully receives fresh data and logs it to the console, the view does not update accordingly. I even attempted using ngZone without success.

Answer №1

It is recommended to use arrow functions in your callbacks in order to utilize lexical this:

constructor(private _websocketService: WebsocketService) {
    _websocketService.observable.subscribe(
        (data) => {
            this.output = data;
            console.log(this.output);
        },
        (error) => {
            console.log(error);
        },
        () => {
            console.log('completed');
    });
}

In this scenario, the reference of this may not be referring to the component instance...

For further insights on the lexical this behavior of arrow functions, refer to this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions.

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

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

What causes the appearance of the "?" symbol at the beginning of the URL and triggers a reboot of the app when moving through the absolute path?

I am facing an issue. In my multi-module application with lazy loading, I encountered a strange behavior when trying to navigate between child lazy modules. Transition from top module to bottom child module works fine, but routing from one bottom child la ...

The Angular Tooltip feature is unable to interpret the characters "' '" or "' '"

Let me explain the scenario: I am receiving a list of objects from my back-end service, which I then break apart using ngFor and display accordingly. Each item in the list has an associated toolTip that provides additional information. The info for each i ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Unlocking the Power of Angular's Default Input Required Validation

Just aiming to utilize the default required validation functionality in HTML. This is the code I've implemented: <form (ngSubmit)="submit()"> <div class="login-container"> <ion-item> <ion-input ...

Exploring Angular 11 Testing: Troubleshooting Async Issues in Jest with RxJS Timer

I encountered an issue while working on a test where I received the following error message: "Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5 ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

ESLint prohibits the usage of React.StatelessComponent and React.FunctionalComponent within the codebase

Is there a way to restrict the use of React.StatelessComponent or React.FunctionalComponent and only allow React.FC in my code? For instance: export const ComponentOne: React.StatelessComponent<Props> = (props) => { return <....> }; export ...

Can someone help me understand why these checkboxes are not properly binding with the two-way binding, even though the opt.checked property is set to true?

<div style="display: table-caption" [id]="question.key" *ngSwitchCase="'checkbox'"> <div *ngFor="let opt of question.options; let i = index" style="display: flex; flex-directi ...

What exactly does bivarianceHack aim to achieve within TypeScript type systems?

As I went through the TypeScript types for React, I noticed a unique pattern involving a function declaration called bivarianceHack(): @types/react/index.d.ts type EventHandler<E extends SyntheticEvent<any>> = { bivarianceHack(event: E): void ...

Tips for importing several makeStyles in tss-react

When upgrading from MUI4 to MUI5 using tss-react, we encountered a problem with multiple styles imports in some files. const { classes } = GridStyles(); const { classes } = IntakeTableStyles(); const { classes } = CommonThemeStyles(); This resulted in ...

Exploring the implementation of initiating paypal in NestJs using Jest testing framework

Currently, I am creating a test for a method within NestJs that is responsible for initiating a Paypal Payment intent. When I execute either the yarn test:watch or simply yarn test command, the test described below runs successfully and passes. However, up ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Angular 4 - Automatically scroll to specific list item based on search query input

While I can achieve this with custom JavaScript, I'm curious if Angular 4 has any built-in features that could help. I have a list of checkboxes that are scrollable and a search input above them. My goal is to enable users to quickly jump to a section ...

TypeScript definition for a dispatcher within a map

I am in the process of creating a typed function that will utilize an object based on its key: const commandOrQuery = { CREATE_USER_WITH_PASSWORD: CreateUserCommandHandler, GET_USERS: GetUsersQueryHandler, }; The structure of commandOrQuery is as foll ...

Creating a personalized Chatbot using Azure Conversation

Looking to customize the conversation with an Azure Chatbot (developed with Typescript) on a webchat or directLine channel (changing the color of the conversation, one for the bot and one for the user, for example). I've been following the guidelines ...

Combining JSON arrays with varying key indices in Typescript

Consider two JSON arrays: A: [ {"id": 123, "name": "AnyName1", "type": "AnyType"}, {"id": 231, "name": "AnyName2", "type": "AnyType"} ] B: [ {"id": 569, "thing": "AnyThing3"}, {"id": 891, "thing": "AnyThing4"} ] The goal is to merge these two arrays re ...

Generate the test output and save it to the distribution folder

When setting up my Angular 9 application in a Jenkins pipeline, I include two key steps: npm run test:prod, which translates to node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod; and npm run build:prod, translating to node --ma ...

Developing an Angular 2 Cordova plugin

Currently, I am in the process of developing a Cordova plugin for Ionic 2. The plugin is supposed to retrieve data from an Android device and display it either on the console or as an alert. However, I am facing difficulty in displaying this data on the HT ...

The control options on the AGM map are experiencing functionality issues

Upon setting the options for agm-maps, I noticed that my options briefly appear and then disappear. This behavior puzzled me, so I decided to create a simple project in Stackblitz to showcase the issue. Below, you'll find the code snippets: code samp ...