Passing a method from a component to a service in Angular 9

Recently, I've been working on some websocket code that involves sending a message to the server and receiving a reply.

The current implementation is functional, but I'm looking to refactor it by encapsulating it within a service and then calling that service from the component instead.

Here is the existing code snippet residing in the component:

import { Component } from '@angular/core';
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  myWebSocket: WebSocketSubject<any> = webSocket('ws://localhost:8888');

  constructor() {

    this.myWebSocket.subscribe(
      msg => console.log('message received: ' + msg),
      err => console.log(err),
      () => console.log('complete')
   );

  }

  sendMessageToServer(msg) {
    const dte = Date.now();
    this.myWebSocket.next({message: `${msg} - ${dte}` });
  }

}

In addition to this, I have created a new service as follows:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class WsService {

  constructor() { }
}

Now the question arises, how should I transition from having the code in the component to utilizing the service? For instance, should the subscription logic be moved to the service or kept in the component?

Answer №1

When providing a service, the goal is to integrate the "subscribe" feature within the component itself. By moving all subscription functionalities to the service, you can streamline the process.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class WsService {
  myWebSocket: WebSocketSubject<any> = webSocket('ws://localhost:8888');

  constructor() {
  }

  sendMessageToServer(msg) {
    const dte = Date.now();
    this.myWebSocket.next({message: `${msg} - ${dte}` });
  }
}

To implement the subscription in the component, subscribe to ws.myWebSocket (it is recommended to subscribe in ngOnInit).

export class AppComponent implements OnInit {
  constructor(private ws:WsService ) {

  ngOnInit()
  {
     this.ws.myWebSocket.subscribe(
      msg => console.log('message received: ' + msg),
      err => console.log(err),
      () => console.log('complete')
   );
  }
  addMessage(msg)
  {
   this.ws.sendMessageToServer(msg)
  }
}

Answer №2

To incorporate the service into your component, follow these steps: 1. Begin by importing your service into the component.

import { WsService} from 'path/to/WsService';

2. Create a local field by adding private wsService: WsService; 3. Include your service in the constructor of the component:

constructor(wsService: WsService)
{
    this.wsService = wsService;
}

4. Utilize your service by calling: this.wsService.Method()

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

Avoid the expansion of line decorations in Monaco editor

I am looking to create a Monaco editor line decoration that remains contained within its original position when I press enter after the decoration. For instance, in a React environment, if I set up a Monaco editor and add a line decoration using the code ...

Is there a method in typescript to guarantee that a function's return type covers all possibilities?

In the case of having a constant enum like: enum Color { RED, GREEN, BLUE, } A common approach is to create a helper function accompanied by a switch statement, as shown below: function assertNever(x: never): never { throw new Error(`Unexpecte ...

Are Angular 4 auth guards implemented on the server side or the client side? And if they are on the client side, are they vulnerable to

While I am engaged in a project using Angular 4, my expertise lies in angular auth-guards. Here's my query: considering that Angular 4 is primarily a client-sided framework, is it possible to bypass the auth-guard by inspecting the browser window, giv ...

Utilizing Typescript to ensure property keys within a class are valid

Looking for advice to make a method more generic. Trying to pass Child class property keys as arguments to the Super.method and have Child[key] be of a Sub class. class Parent { method<T extends keyof this>(keys: T[]){ } } class Child extends P ...

Error 401 encountered while accessing the Binance API using Ionic and Angular

function makePrivateCall(apiSecret, apiKey, endpoint, data = null, isGetRequest = true) { const timestamp = Date.now(); const recvWindow = 60000; //maximum allowed, default 5000 var obj = { apiSecret, ...data, timestamp, ...

There is no ElementRef present in the HeaderComponent type

Task: Implement code to detect mouse clicks inside or outside a specified component, leading to an error message stating that 'elementref' does not exist within the 'Headercomponent' type. import { OnInit, Input, Output, ElementRef } f ...

The image is malfunctioning in the production environment, but functions perfectly on the localhost server

Currently, I am in the process of creating a website utilizing Next.js and Mantine. In order to incorporate my logo into the Header section, I utilized the Image component from next/image. Unfortunately, upon deployment, the image does not display as inten ...

Form a collection using multiple elements

I'm attempting to combine multiple arrays into a single array. For instance : array1= ['Joe','James','Carl','Angel','Jimmy',]; array2= ['22','11','29','43',&apo ...

"Exploring the power of Angular 16 coupled with Firebase 9 for seamless file

Recently, I've been facing some challenges with my Angular 16 app that uses Firebase 9 and angular/fire 7. Specifically, I've been struggling to implement a simple file upload feature to Firebase storage. Despite spending the last couple of days ...

Efficiently loading Ionic 3 components within a tab with lazy-loading functionality

Need help with adding a new tab to your project using lazy-loading? You can utilize the @IonicPage decorator for setting up a page as the root of a tab. To implement this, create a new page: // module import { NgModule } from '@angular/core'; ...

Identifying the pressed key on a mouse click event using Angular 2

I am working on an Angular 2 component that has a div element bound to a click event: <div #myDiv class="myClass" (click)="addAnnotation($event)"> </div> When the div is clicked, I want the addAnnotation code to run only if the 'a&ap ...

Exploring TypeScript nested interfaces and types within VSCode

I often find myself hovering over functions or objects in VSCode with TypeScript to inspect their type. However, many times the types and interfaces of these objects are dependent on other interfaces and types, making it difficult to get detailed informat ...

Angular 6: Utilizing async/await to access and manipulate specific variables within the application

Within my Angular 6 application, I am facing an issue with a variable named "permittedPefs" that is assigned a value after an asynchronous HTTP call. @Injectable() export class FeaturesLoadPermissionsService { permittedPefs = []; constructor() { ...

What could be causing the lack of updates in my SolidJS component when the data changes?

One of my components in SolidJS is an Artist page component. Here is a snippet of the code: export function Artist() { const params = useParams<{ id: string }>(); const [data, setData] = createSignal(null); createEffect(() => { fetchArti ...

Troubleshooting: Issue with Angular 2 bidirectional data binding on two input fields

Hi there, I am encountering an issue with the following code snippet: <input type="radio" value="{{commencementDate.value}}" id="bankCommencementDateSelect" formControlName="bankCommencementDate"> <input #commencementDate id="bankCommencementDat ...

Tips for transitioning from Angular to Angular 2: Overcoming key challenges

Our current Angular project is highly developed, but with the emergence of Angular 2 and its advanced features and improved performance, we are considering migrating our existing work. However, we are concerned about the potential challenges that may ari ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

Merge arrays values with Object.assign function

I have a function that returns an object where the keys are strings and the values are arrays of strings: {"myType1": ["123"]} What I want to do is merge all the results it's returning. For example, if I have: {"myType1": ["123"]} {"myType2": ["45 ...

Since updating from Angular 16 to 17, I am experiencing a TypeScript compilation issue specifically related to 'openui5'

Everything was running smoothly in Angular16. I had "@types/openui5" : "1.40.4" listed in my dev-dependencies. Here is how it's configured in the tsconfig.json: { "compilerOptions": { "downlevelIteration": ...

Display Material UI icons as markers within Highcharts

Does anyone know how to use Material UI icons as markers in rendering? I have been searching for documentation but can't seem to find a clear explanation. Any guidance would be greatly appreciated! ...