A More Straightforward Approach to Unsubscribing from Observables in Angular 7

Is there a way to simplify the process of automatically unsubscribing from Observables when a component is destroyed using takeUntil? It becomes tedious having to repeat the same code in multiple components.

I am looking for a solution that allows me to access emitted values in the Typescript component without using the async pipe.

Would appreciate any suggestions on streamlining the current implementation below:

export class Component implements OnDestroy {
    _dstr = new Subject();

    data$: Observable<any> = this.store.select(Selector.getData);

    constructor(
        private store: Store<State>,
    ) {
        this.store.pipe(
            select(Selector.getOtherData),
            takeUntil(this._dstr),
        ).subscribe(data => {
            console.log('here is my data!', data)
        });
    }

    public ngOnDestroy(): void {
        this._dstr.next();
        this._dstr.complete();
    }

}

Answer №1

To efficiently manage subscriptions in Angular, one approach is to gather all subscriptions in an array and unsubscribe each one in the ngOnDestroy function. If this is a recurring need, consider utilizing an abstract class that all components can extend, automating this process for you.

import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subscription, Observable, of } from 'rxjs';

export abstract class BaseComponent implements OnDestroy{
  public subscriptions: Subscription[] = [];

  public ngOnDestroy(): void {
    console.log("destroyed");
    this.subscriptions.forEach(s => s.unsubscribe());
  }
}

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

}

let count: number = 0;
@Component(
  {
    selector: 'app-derived',
    template: 'Derived Class'
  }
)
export class DerivedComponent extends BaseComponent implements OnInit, OnDestroy {
  private store: Observable<any> = of(count++);
  constructor() {
    super();
  }
  public ngOnInit(): void {
    this.subscriptions.push( this.store.subscribe(data => console.log(data)) );
  }
}

Check out the Blitzstack demo here: https://stackblitz.com/edit/angular-peyoac

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

Angular - Is there a specific type for the @HostListener event that listens for scrolling on the window?

Encountering certain errors here: 'e.target' is possibly 'null'. Property 'scrollingElement' does not exist on type 'EventTarget'. What should be the designated type for the event parameter in the function onWindow ...

Modifying the value of a React input component is restricted when the "value" field is utilized

I'm currently utilizing material-UI in my React application. I am facing a challenge where I need to remove the value in an input field by clicking on another component. The issue arises when using the OutlinedInput component with a specified value. ...

Tips for utilizing the "this" keyword in TypeScript

As a newcomer to TypeScript, I am seeking assistance on how to access the login service within the authenticate function. Despite using the 'this' keyword to retrieve the login service, it seems ineffective. Additionally, I find myself puzzled by ...

Monitor changes in input display within ngIf statements

Within my code, I am utilizing an input element within a conditional statement of *ngIf: <div *ngIf='display'> <input number="number" /> </div> My goal is to be able to detect the visibility state of the input element insi ...

Utilizing Loops to Generate Unique CSS Designs on an HTML Page

View reference image ->Take a look at the reference image provided. ->In the image, a for loop is used to create box designs and displayed above. ->The goal is to change the background color and border color of all boxes using a single HTML cla ...

Failed to load module chunk: Please update to angular 7

I am encountering an issue with my application hosted on IIS after upgrading to Angular 7. The error message "Loading chunk module failed" indicates that instead of fetching files from the dist/ folder, it is attempting to fetch them from the root folder. ...

Transforming the timestamp to a date object using Angular and Typescript

As a newcomer to Angular 2.0, I've been delving into new concepts in order to grasp it better. However, despite encountering this common issue multiple times and reading through various solutions, I haven't been able to find the answer to my prob ...

"Curious why the change event doesn't trigger when selecting an option that is already selected

Angular reactive forms are causing an issue where the change method for select field does not fire when selecting an already selected option. You can view an example of this behavior at the following link: https://stackblitz.com/edit/angular-2e1cvz. In t ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

The name 'SafeUrl' cannot be located

I'm working on resolving the unsafe warning in the console by using the bypassSecurityTrustUrl method, but unfortunately, I keep encountering an error. user.component.ts import {Component,OnInit} from '@angular/core'; import { DomSanitizer ...

Using Flickity API in Vue 3 with Typescript Integration

I have encountered an issue with implementing Flickity in my Vue 3 application. Everything works perfectly fine when using a static HTML carousel with fixed cells. However, I am facing difficulties when attempting to dynamically add cells during runtime us ...

The function response.body.getReader is not defined

While making a call to a web api using fetch, I encountered an issue when attempting to read the response as a stream. Despite calling getReader() on response.body, I received the error message: "TypeError: response.body.getReader is not a function". ...

generating declaration files for components with accurate type definitions from propTypes

I am in the process of creating a react/js library using rollup. My approach involves utilizing typescript to generate declaration files for my components. Despite having propTypes defined for my components, I have noticed that the emitted .d.ts files as ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

Guidelines for utilizing a loader to handle a TypeScript-based npm module

I am currently facing a challenge with my React and JavaScript project as I attempt to integrate an npm module developed with TypeScript. The issue lies in configuring my project to compile the TypeScript code from this module, resulting in the error messa ...

Modifying the default FilterSettings in ejs-grid: A step-by-step guide

Brand new to Angular and Material technologies, I recently created a grid following the instructions provided here. Below is the html template for the table: <ejs-grid #grid [dataSource]='data' allowFiltering='true' allowPaging=& ...

Tips for adding a mat-error to a mat-input-field on-the-fly

To handle user input exceeding maxLength and dynamically add < mat-error > to the DOM in case of an error, I have implemented an attribute directive that enforces the character limit on input fields. This directive is used across multiple files in th ...

Undefined output in Typescript recursion function

When working with the recursion function in TypeScript/JavaScript, I have encountered a tricky situation involving the 'this' context. Even though I attempted to use arrow functions to avoid context changes, I found that it still did not work as ...

Assignment on Ionic's Cascading Style Sheets classes

As I work on styling my app, I find myself struggling with the extra CSS classes that are added when I preview the source in a running app. It's particularly confusing when all I want to do is change the menu header background. In my app.html file, I ...

Why is webpack attempting to package up my testing files?

In my project, I have two main directories: "src" and "specs". The webpack configuration entrypoint is set to a file within the src directory. Additionally, the context of the webpack config is also set to the src directory. There is a postinstall hook in ...