What is the best way to refresh content in a secondary component when a websocket event is received by the primary component?

My Component A has a websocket logic that looks like this:

    this.socketService.connect('/socket_url');
    this.statusSubscription = this.socketService.messages
      .subscribe(result => {
        if (result !== 'pong') {
            // update Component B with the received response
        }
    });

I'm curious about how I can keep Component B updated whenever a websocket event is triggered.

Answer №1

If you want to utilize a shared Service and Observable, here's how you can do it.

shared-data.service.ts

import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class SharedDataService {

  public userStatusToggle: Observable<any>;
  private userStatusSubject = new Subject<any>();

  constructor() {
    this.userStatusToggle = this.userStatusSubject.asObservable();
  }

  notifyUserStatusChange(data) {
    this.userStatusSubject.next(data);
  }
}

Component A

.
.
.

constructor(private  sharedDataService: SharedDataService) {    
}

this.socketService.connect('/socket_url');
this.statusSubscription = this.socketService.messages
        .subscribe(result => {
            if (result !== 'pong') {
                this.sharedDataService.notifyUserStatusChange(result);
            }
        });

Component B

.
.
.
constructor(private  sharedDataService: SharedDataService) {    
}

this.sharedDataService.userStatusToggle.subscribe(userStatus => {
    // Perform an action using the obtained 'userStatus'
});

Answer №2

If you have components in a parent/child relationship, you can achieve the same result by following these steps:

Parent Component (Component A):

this.socketService.connect('/socket_url');
    this.statusSubscription = this.socketService.messages
      .subscribe(result => {
        if (result !== 'pong') {
            this.componentBdata = result;
        }
    });

In componentA.html

<componenB [data]="componentBdata "> </componentB>

Child Component (Component B):

export class ComponentB implements OnChanges, OnInit {
  @Input() data: string;
  private _data: string;
  constructor() {}

  ngOnChanges(changes: SimpleChanges) {
    const data: SimpleChange = changes.data;

    if(data.previousValue ! = data.currentValue){
       this._data = data.currentValue;
       // implement your logic here based on the change
    }
  }

}

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

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

Utilizing Three.js to Create a PlaneGeometry that Completely Fills the

Excited to explore THREE.JS, I'm currently working on an Angular project to create a waving flag animation. Check out my progress so far: https://stackblitz.com/edit/angular-edgwof?file=src/app/app.component.ts My goal is to ensure that the plane fi ...

Changing md-sidenav mode in Angular Material 2

Looking to modify the behavior of the md-sidenav in Angular Material 2, switching from side on desktops to over on mobile devices. Is there a method to achieve this programmatically? Appreciate any guidance! ...

Seeking assistance with TypeScript promises

Just starting out with typescript and nodejs, but I've got to tackle some issues in the typescript code. I'm looking to execute an ECS one-off task using Pulumi. I have the documentation on how to run the task from the taskDefinition, which can ...

Setting up pagination in Angular Material can sometimes present challenges

After implementing pagination and following the guidelines provided here. This is my code from the app.component.ts file - import { Component, OnInit, ViewChild } from '@angular/core'; import {MatPaginator} from '@angular/material/paginat ...

TypeOrm is struggling to identify the entities based on the directory path provided

Currently, I am utilizing TypeORM with NestJS and PostgreSql to load entities via the datasource options object. This object is passed in the useFactory async function within the TypeORM module as shown below: @Module({ imports: [TypeOrmModule.forRootAsy ...

An issue detected in the index.esm.js file located in the firebase/firestore module within the node

I've encountered an issue while starting my angular project using the npm-start command. Here is the error I came across: ERROR in ./node_modules/firebase/firestore/dist/index.esm.js Module not found: Error: Can't resolve '@firebase/firest ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

Combining divs with identical values in Angular

I am working on creating my very own custom Calendar. Take a look at the full example of my component here I need help figuring out how to combine week divs that share the same value {{day.weekNumber}} so that there is only one div for each shared value, ...

Issue with HttpClient causing malfunction

I'm currently using Angular 4 and have decided to transition to using HttpClient. However, I've encountered a JSON parsing error that has proven quite challenging to fix despite extensive research. Previous Method import { Injectable } from &ap ...

Tips for outputting data in TypeScript when a search form is updated

Below is the structure of my HTML file: <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type"" content="text/html; charset=utf-8"/> </head> <body> <input ...

When using VS Code, custom.d.ts will only be recognized if the file is currently open in the

I have created some custom Typescript declarations in a custom.d.ts file. When I have this file opened in VS Code, everything works correctly and the types are recognized. However, when I close the file, VS Code does not recognize these definitions, leadin ...

One method to make this code more concise

Is there a way to condense this code? I want 'All' to be displayed at index 0. Can I have multiple conditions, such as displaying 'All' at index 0, performing an action at every other index, and another action at the last index? I enc ...

Simulate a complete class with its constructor, instance methods, and static functions

I have been searching for a comprehensive example that demonstrates how to properly mock all three elements (ClassA constructor, ClassA.func1 instance function, and ClassA.func2 static function) in my TypeScript project. In the code under test, I need to v ...

What is the importance of including "declare var angular" while working with Typescript and AngularJS?

I've been working on an AngularJS 1.7 application that's coded entirely in TypeScript, and there's always been one thing bothering me. Within my app.module.ts file, I have this piece of code that doesn't sit right with me: declare va ...

Tips on integrating Pagination in Angular Carbon Design System without relying on a TableModel

We are working with an array of objects (Paper) and utilizing a Search filter. Here is our code snippet in .html: <ibm-search placeholder="Search title" (clear)="clearSearch()" [(ngModel)]="listFilter" >Search</ibm-search> &l ...

You cannot assign void to a parameter expecting a function with no return value

I have been working on an angular application that was initially developed in Angular 2, then upgraded to versions 7 and 9, and now I'm attempting to migrate it to Angular 11. There is a function in my code that fetches the notification count for the ...

Tips for maintaining an active Angular PWA while your device is in doze mode

We are currently in the process of creating an angular progressive web application that receives updates from a LightStreamer Server and displays notifications to the user. Since PWAs serve as alternatives to native apps, we are aiming for our app to rem ...

Creating web components with lit-element, leveraging rollup, postcss, and the tailwind framework for packaging

I have been attempting to package a functional web component that was developed using the lit-element/lit-html with the tailwind framework utilizing the postcss plugin from the rollup packager. Upon conducting a rollup, I discovered the compiled js and ht ...

Experimenting with axios.create() instance using jest

I have attempted multiple solutions for this task. I am trying to test an axios instance API call without using any libraries like jest-axios-mock, moaxios, or msw. I believe it is possible, as I have successfully tested simple axios calls (axios.get / axi ...