Is it considered acceptable to share your RxJS Subjects with the public eye?

I recently came across a fascinating article about the Angular onPush Change Detection Strategy

where the author highlighted:

Avoid exposing your subject to external sources; always expose the observable instead by utilizing the asObservable() method.

However, he did not elaborate on the reasons behind this recommendation. Does this imply that actions such as the following should be avoided?

export class ExampleComponent {

  public drawerTrigger$ = new Subject<{}>(); 
}

In the HTML file:

  <button  class="hamburgher-button" type="button"
     (click)="drawerTrigger$.next($event)">
    <i >menu</i>
  </button>

If not, what is the correct approach to handling this situation?

Answer №1

It is generally not recommended to expose Subjects in your code because it opens up the possibility for others to misuse them, such as uncontrollably calling drawerTrigger$.next().

Even more concerning is that exposing a Subject allows users to call drawerTrigger$.error() or drawerTrigger$.complete(), which can lead to the Subject being marked as stopped and unable to emit any more values. By exposing your Subject, you are giving others the ability to trigger these notifications.

The preferred method of exposing Subjects from TypeScript classes is by strictly typing them as Observable. You do not need to use asObservable() (since RxJS does not internally use this method anywhere in its codebase):

export class ExampleComponent {
  private drawerTriggerSubject = new Subject<{}>(); 
  public drawerTrigger$: Observable<{}> = this.drawerTriggerSubject;
}

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 is the command line method for running ESLint in flat configuration?

When using the flat config for eslint.config.js, how can I lint *.js files recursively from the command line? 1 In the past with eslintrc.js or eslintrc.json, I have used npx eslint . --ext .js, as mentioned here. Up until now, it has always worked withou ...

What is the best way to dynamically import two css frameworks in React?

Currently, I am involved in a project that requires me to incorporate a button for toggling between Bootstrap and Foundation at the request of my client. After exploring several alternatives, I have determined that utilizing hooks to manage the state of e ...

Exploring Angular 2: Performing an HTTP GET Request with Specific ID

I am encountering an issue with my http get request for a specific object. I pass the ID in the request, but on the serverside, the value is showing up as ${id} instead of the actual passed number. I'm not sure what I'm doing wrong, especially si ...

When passing the parameter in Angular, the value appears as "Ébénisterie," but in Java, it is retrieved as "Ã?bénisterie"

In Angular, there is a parameter with the value Ébénisterie. However, when I try to print the same variable in Java, it displays as Ã?bénisterie. Can someone help me convert it back to the original text Ébénisterie? Which encoding/decoding process ...

What triggers Angular's Change Detection mechanism when binding to a function?

After reading these two informative articles: Exploring the mechanics of DOM updates in Angular Is it more efficient to bind with a data member than a function in Angular 2 Performance? I have a good understanding of how the DOM is updated when 'C ...

Angular: Retrieve the source after navigating

Hello there, I am facing a simple problem. I have 2 components navigating to 1 component and in that one component, I need to distinguish which component the navigation came from so I can take appropriate action (such as refreshing a list). The issue is t ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

Creating Typescript declarations for local JavaScript files

As part of our transition to Typescript at work, I've been working on adding typings to our Javascript files. However, I'm facing an issue with getting the declaration files recognized. Below is my file structure: js Foo.js typings Foo ...

The specified file 'node_modules/bingmaps/types/MicrosoftMaps/Microsoft.Maps.d.ts' cannot be treated as a module

Currently utilizing the official npm package for bingmaps with angular 7 (cli). I have followed the configuration instructions outlined in the npm documentation, and I am successfully loading the basic bing map. In my component.ts file, I included the ...

The default filter in Angular Material Autocomplete is failing to function as expected

I've implemented the Autocomplete feature from Angular Material in my project, but I'm facing an issue with the search filter. It seems that the default filter provided in the example is not working as expected – instead of filtering based on m ...

How to simultaneously send multiple GET requests in Angular 2

By utilizing a promise JS library (https://github.com/stackp/promisejs), I am able to achieve the following: promise.join([ promise.get('/settings'), promise.get('/translations'), promise.get('/main-data') ]).then ...

The "(click)" event doesn't fire upon clicking a material icon

After creating an <a> tag with a (click) event function call, I noticed that the click event works everywhere except for the arrows mat-icons within the code snippet below: <span *ngIf="section.pages.length>0"> <mat-icon *ngIf="secti ...

The table elements do not align properly with Bootstrap styling

I utilized the bootstrap table to create a table, but unfortunately, the fields are not displaying correctly. How can I rectify this issue? Only the first field is accurate. https://i.sstatic.net/vkKkR.png ...

TypeScript in Angular causing lodash tree shaking failure

I am currently working on a large project that involves TypeScript. Various attempts have been made to optimize the use of lodash in my project. Before making any conclusions, I believe it is important to review the outcomes of my efforts. The command I ...

What is the best way to transform a string into a template reference object?

In the process of setting up ngTemplateOutlet within *ngFor, I encountered an issue similar to that outlined in the code snippet below. <ul> <li *ngFor="let item of list"> <ng-container [ngTemplateOutlet]="item.type"></ng- ...

How do I utilize the file handler to execute the flush method within the Deno log module using Typescript?

I'm having trouble accessing the fileHandler object from my logger in order to flush the buffer to the file. This is the program I am working with: import * as log from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

Creating dynamic HTML in Angular 2 can be achieved by utilizing directives, data

I am interested in building an accordion feature in angular2 without needing to duplicate the structure each time it is used. Similar to how we can create plugins in jQuery and include HTML code, I would like to find a way to achieve this in Angular2. Ca ...

How is it possible that there is no type error when utilizing copy with spread syntax?

When I use the map function to make a copy of an array of objects, why doesn't it throw an error when adding a new property "xxx"? This new property "xxx" is not declared in the interface. interface A{ a:number; b:string; }; let originalArray:A[] ...

Guide on initializing a Redux toolkit state with an array of objects or local storage using TypeScript

Currently, I am attempting to set an initial state (items) to an array of objects or retrieve the same from localStorage. However, I am encountering the following error. Type 'number' is not assignable to type '{ id: string; price: number; ...

There seems to be an issue with functionality, as undefined is not behaving as expected in the combination of Graph

I am encountering an issue in my react native project where I am utilizing graphql codegen for generating types and hooks. The current version of react native that I am using is 0.74.5. However, I am facing an error which is preventing me from launching my ...