Sign up for Observable and receive notifications for specific events

I am working with an Angular service that looks like this:

export class EventService {

  private subject = new Subject<Event>();

  send(code: EventCode, data?: any) {
    this.subject.next(event);
  }

  clear() {
    this.subject.next();
  }

  get(): Observable<Event> {
    return this.subject.asObservable();
  }

}

The classes used in the service are Event and EventCode:

export class Event {
  code: EventCode;
  data: any;
  constructor(code: EventCode, data?: any) {
    this.code = code;
    this.data = data;
  } 
} 

export enum EventCode {
  Created,
  Deleted,
  Updated
}

When using the service, I subscribe to events like this:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

Now, I want to only subscribe to Events with a specific EventCode.

Is there a way to achieve this functionality? How can I implement it?

Answer №1

Let's start by addressing this:

this.eventService.get().subscribe((event: Event) => { 
  // Do something 
});

If you don't unsubscribe, it will lead to memory leaks when the component is destroyed. Here's a better approach:

export class MyComponent implements OnInit, OnDestroy {
  // store subscription
  private eventServiceSubscription: Subscription;

  ngOnInit() {
        this.eventServiceSubscription = this.eventService.get().subscribe((event: Event) => {
          // check event code
          if(event.code === 'someEventCode') {
            // process event
           }
         });
   }

   ngOnDestroy() {
     this.eventServiceSubscription.unsubscribe();
   }
}

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

An error is encountered when attempting to retrieve the list using axios

For this project, I am required to fetch a list from the following resource: http://jsonplaceholder.typicode.com/photos The controller setup is as follows: @JsonController('/photo') @Service() export class PhotoController { const ...

Is there a way to incorporate TypeScript type definitions into a JavaScript module without fully transitioning to TypeScript?

Although the title may be a bit confusing, it encapsulates my query in a succinct manner. So, here's what I'm aiming to achieve: I currently have an npm module written in JavaScript, not TypeScript. Some of the users of this module prefer using ...

Error in Jest: Type error - res.status function is undefined

I have implemented a middleware for token verification using the following code: import { Request, Response, NextFunction } from "express"; import jwt from "jsonwebtoken"; class TokenVerifier { public verify(req: Request, res: Resp ...

Encountered a 400 error when trying to install Angular CLI on Windows 10 through a proxy server

Recently delving into Angular, I encountered the need to install Angular CLI on my Windows 10 PC behind a proxy server. Running Node v12.13.1 and npm v6.12.1, I followed the steps of copying the script address value from Proxy settings and updating the con ...

Pattern for defining objects with indexes in Typescript

My data is structured as shown below: let equipment:Equipment = { "1": { "name": "abc", "data": 123 }, "2": { "name": "def", "data": 234 }, "3": { "name": "ghi", "data": 345 }, ... } Converting this into an array se ...

Tips for assigning a value to a Reactive Form control within Angular 6

I am looking to dynamically set the value of a text box when clicking on a button that is located outside of the form. How can I achieve this? <form [formGroup]='student' (ngSubmit)='click()'> <input type='text' form ...

Having trouble with this.$.... not functioning properly post migration from Vue2 to Vue3

Recently, I began the migration process using the migration guide and the Compat build to ensure a smoother transition. Here is how I have configured the vue.config.js: chainWebpack: (config) => { // Set alias for Vue compatibility build config.resolve. ...

When using an Angular2 application that relies on an external reference to Auth0Lock, the application encounters a NotFound error when executed

For my latest project, I decided to create an app using angular2-seed as a base. Everything was going smoothly until I tried deploying the production build on an Azure website. To my surprise, I encountered an issue when trying to load the page: > Refe ...

Error: The file named '/accounts.ts' cannot be recognized as a module within a Node.js API

After researching this issue, I have found some answers but none of them seem to solve my problem. Below is the code in my model file: // accounts.ts const mongoose = require('mongoose'); var autoincrement = require('simple-mongoose-autoi ...

Create a d.ts file for Vue components that are written using Typescript

As a newcomer to Vue, I am eager to dive into creating components and publishing packages to NPM. My plan is to develop Vue (typescript) + Vuetify reusable components that can be easily installed from NPM into any of my projects. While I have successfully ...

Having trouble with triggers: Unable to locate the module 'csv-parse/sync' for parsing

Currently, I am utilizing Firebase functions to create an API that is capable of parsing CSV files. However, whenever I attempt to utilize csv-parse/sync instead of csv-parse, my deployment to Firebase Functions encounters a failure with the subsequent er ...

angular2 : problem encountered with communication to rest api

Transitioning from PHP to Angular2 has been quite challenging for me, especially when trying to use a real rest API like "Tour of Heroes". I initially thought it would be simple... Currently, I have set up a functional API with Express: curl -XGET http:/ ...

Navigating with Conditions in Angular 2

I have two main components in my Angular application - Home and Login. The Login component serves as the default page, and once a user logs in, I want them to navigate to the Home component. Within my app.router.ts file, the routing configuration is set u ...

Firebase deployment triggers multiple errors

After developing Firebase Cloud Functions using Typescript in VS Code, I encountered an issue. Despite not receiving any errors within VS Code itself, numerous error messages appeared when deploying the Firebase code. What could be causing these errors, an ...

Which is better for narrowing object property types: using dot notation or object literal notation?

Is there a reason why type narrowing by assignment behaves differently based on whether we use dot notation or object literal notation? Below are two examples to illustrate this discrepancy. type MyObj = { x?: number | string } let obj1: MyObj = {} obj1.x ...

Tips for fixing the TypeError related to hasOwnProperty in your index.tsx file

I need assistance setting up a basic frame for my TypeScript project as I am having trouble compiling it. Any guidance would be greatly appreciated. The error I am encountering is: in ./app/index.tsx Module build failed: TypeError: Cannot convert undefin ...

I am unable to add a new property to the request object in the Express framework

My goal is to add a new property to the request object in typescript. Here's the code snippet I'm using: import { request, Request, response, Response } from "express"; ((req: Request, res: Response) => { console.log(req.user); ...

What steps should I take to avoid harmful automatic approvals during application launch while utilizing the "angular-auth-oidc-client"?

Utilizing the "angular-auth-oidc-client" in my app is crucial, operating in mode "silent_run": true. The app initiates with various routes, always accompanied by query parameters. Majority of the resources within the application do not necessitate server a ...

The art of Angular localization: harvesting language elements from ts documents

Is it true that $localize is only available for translation in ts files, but the extraction of strings is currently only implemented for templates? I came across information stating that the extraction of strings from ts files should be possible in Angular ...

Retrieve an additional 10 items from the API when the button in the Angular list is clicked

I need to display 10 items each time the button is clicked. Below is the code snippet for the services: import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' @Injectable({ providedIn: ' ...