Stopping HTTP client calls in OnDestroy hook of an Angular Service

Is it possible to automatically unsubscribe from an http call in an Angular service using the ngOnDestroy hook?

Just to note, I am already familiar with using the rxjs 'take' operator or manually unsubscribing from the service within the component itself.

    import { HttpClient } from "@angular/common/http";
import { Injectable, OnDestroy } from "@angular/core";

@Injectable()
export class SampleService implements OnDestroy {
  constructor(private httpClient: HttpClient) {}

  getSampleData() {
    return this.httpClient.get("https://jsonplaceholder.typicode.com/todos/1");
  }
  ngOnDestroy(): void {
    // handle automatic unsubscription here
  }
}

Answer №1

Services operate independently of user interface-driven lifecycles, meaning that the onDestroy method will not be triggered automatically unless you manually invoke it.

Fortunately, there are tools and APIs available to handle this situation:

<div> {{ yourObservable$ | async | json }} </div>
@Component({...})
export class Component implements OnInit {
   yourObservable$: Observable<any>
   constructor(public yourService: TheService) {
       this.yourObservable$ = this.yourService.getSampleData()
   }
}

The async pipe automatically handles lifecycle changes by subscribing and unsubscribing when the component is destroyed

  • Subscription (you can add other subscriptions using .add) and in your component's onDestroy method, call subscription.unsubscribe()

The async pipe relies on Subscription.unsubscribe, which you can also utilize on your own

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

Using AngularJS to show content based on a callback function

I'm a beginner in angular and it seems like I might be overlooking something. For the registration form, I need users to provide their location. Depending on whether they allow/support navigator.geolocation, I want to display a drop-down menu for cho ...

Searching for a specific field within an array in a nested subdocument in MongoDB: What you need to know

I am having trouble retrieving lookup data for an embedded array within a document. Below is a snippet of the data: { "_id": "58a4fa0e24180825b05e14e9", "fullname": "Test User", "username": "testuser" "teamInfo": { "chal ...

Utilizing a conditional ngIf statement in HTML or incorporating a variable within typescript for logical operations

When working with our application, we often need to display or hide a button based on specific logic. Where do you think it is best to define this logic and why? In HTML: *ngIf='logic goes here' //Or *ngIf='someBoolean' and in Type ...

Arranging data using jqGrid's Inline Editing Feature

Can the data on jqGrid be sorted directly on the client side while using inline editing? It appears that the data is not being sorted when the row is editable, even if the row header is clicked. ...

Looking to switch up the hide/show toggle animation?

Currently, I have a functioning element with the following code. It involves an object named #obj1 that remains hidden upon page load but becomes visible when #obj2 is clicked. #obj1{ position:fixed; width:100px; bottom:180px; right:10 ...

Is it possible in Vue.js to create a reactive functionality for a button using a watcher for "v-if" condition?

I have a userlist page with various profiles, including my own. A button is supposed to appear only when viewing my own profile. The issue arises when switching from a different profile to my own (changing the router parameter) - the button should show up ...

Is there a way to package extra files along with `NodejsFunction` in Node.js?

I am looking to add another HTML file to the source code, like shown below. https://i.sstatic.net/OyxDM.png Here is my current code: const mailerFunction = new aws_lambda_nodejs.NodejsFunction(this, 'ApiNotificationHandler', { runtime: lambd ...

You are not able to access the instance member in Jest

My first encounter with Javascript has left me puzzled by an error I can't seem to figure out. I'm attempting to extract functions from my class module in order to use them for testing purposes, but they remain inaccessible and the reason eludes ...

Guide to building a seamless page without refreshes with the help of jquery, express, and handlebars

I need assistance with my express JS project. I am trying to set up two pages using NodeJS, incorporating handlebars as the template engine. My objective is to have the first page rendered using res.render('home'), and for the second page to be l ...

Having Difficulty Applying a Background Color to a Class in Bulk

I am working on a unique HTML canvas for pixel art, which is created using a table made up of various divs all sharing the "pixel" class. I want to add a clear button that can reset the entire canvas, but changing the background color of each individual di ...

AngularJS - Setting an initial delay for ng-bind

We have a span element with the following attributes: <span role="link" ng-show="showLink()" ng-bind="textLink"></span> (Just an fyi: we implemented a fade-in, fade-out animation for this link, hence the use of ng-show instead of ng-if) The ...

I encountered an issue with rate-limiter-flexible where I received an error stating that the Lua redis() command arguments need to be either

I have implemented rate limiting using the rate-limiter-flexible library const redis = require('redis'); const { RateLimiterRedis } = require('rate-limiter-flexible'); This is the code snippet I am working with // Create a Redis client ...

What is the most efficient way to dynamically add a class to multiple elements in AngularJS using ng-click?

On my HTML page, I have 2 lists that I want to modify so that when an option is clicked, it adds a class altering the background-color of the li element to red. If the same option is clicked again, it removes the class and reverts back to white: This is t ...

Update the color of navigation items to reflect their active status

Here is the snippet of HTML code: <header> <nav> <a href="#" id="menu-icon"></a> <ul> <li><a href="#"">Home</a></li> <li><a href="#">About</a></li> & ...

The function array.push() is not achieving the intended outcome that I had in mind

Currently facing a rather frustrating issue. I'm attempting to utilize D3.js for dynamically plotting data (specifically, scores of individuals). Retrieving record data from a firebase database whenever changes occur - this is represented by an obje ...

Implementing Bootstrap 5 JS within an Angular 11 component TypeScript

I am currently working on a project that utilizes Angular 11 and we are aiming to integrate Bootstrap 5 native JS without relying on third-party libraries like ng-bootstrap, MDB, or ngx-bootstrap (jQuery is not being used as well). I understand that using ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

How can elements with class prefix names be retrieved in IE Browser Helper Object using c#?

I've been developing an IE Plugin using BHO and I need to access an element based on its class prefix in C#. In JavaScript and jQuery, I was able to accomplish this with the following code: var myClass = $('[class^="ii gt"]'); and var myC ...

Retrieving JSON data in Angular 2

There are limited options available on SO, but it seems they are no longer viable. Angular 2 is constantly evolving... I am attempting to retrieve data from a JSON file in my project. The JSON file is named items.json. I am pondering if I can achieve th ...

TinyMCE toolbar missing the "hr" option

I am encountering an issue while using TinyMCE as my editor. I have added the plugin as instructed, but I cannot find the "hr" button/option in the editor interface. If anyone has any insights or solutions to this problem, please share! This is how I am ...