Stop the observable interval in Angular when the route changes

I initiated an interval in an Angular component, but the requests are still being made even when I navigate to a different route. How do I halt the interval?

//function that returns an observable
getAllPolls() {
    return Observable.interval(2000).switchMap(() => this._http.get('https://xq4kftam4k.execute-api.us-east-1.amazonaws.com/test/polls2'))
        .map((res: Response) => res.json())
}

Answer №1

Make sure to retain the subscription to the observable:

this.pollSubscription = fetchAllPolls().subscribe(...);

Additionally, include the OnDestroy interface:

  ngOnDestroy() {
     this.pollSubscription.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

A guide on incorporating JavaScript variables within a GraphQL-tag mutation

I'm having trouble consistently using javascript variables inside graphql-tag queries and mutations when setting up an apollo server. Here's a specific issue I've encountered: gql` mutation SetDeviceFirebaseToken { SetDeviceFirebaseTok ...

Dynamic placeholder modification depending on form selection

How can I dynamically change the placeholder text based on user selection? //div with a toggle for two options <div fd-form-item> <label fd-form-label for="select-targetType">Showroom type:</label> <select class=&q ...

Guide on integrating Amazon S3 within a NodeJS application

Currently, I am attempting to utilize Amazon S3 for uploading and downloading images and videos within my locally running NodeJS application. However, the abundance of code snippets and various credential management methods available online has left me fee ...

The system detected an Image with the source "/images/logo.png" as the primary element contributing to Largest Contentful Paint (LCP)

I have been working on a project using Next.13 and Typescript. In order to display an Image, I created a component called Logo.tsx. "use client"; import Image from "next/image"; import { useRouter } from "next/navigation"; c ...

Angular 5 Dilemma: Exporting UI Components without Locating Template

My current project involves developing UI Components that will be used in various web projects within the company. Our plan is to publish these UI components as an npm package on our local repository, and so far, the publishing process has been successful. ...

What is the essential Angular 2 script that must be included for a simple Angular 2 application to function properly?

I'm currently working through the latest Tuts+ tutorial on Angular 2 In the tutorial, the author references adding this script: <script src="node_modules/angular2/bundles/angular2.sfx.dev.js"></script> However, in the most recent beta re ...

I'm experiencing a lack of data appearing on my AngularFire application

Every time I attempt to display my data using the following code snippet: <li *ngFor="let course$ of courses$ | async"> <pre>{{ course$.title }}</pre> </li> Unfortunately, with angularfire2 I am unable to see any data. Upon co ...

What is the best way to include the parameter set in the interceptor when making a post request?

-> Initially, I attempt to handle this scenario in the axios request interceptor; if the parameter is uber, then utilize a token. If the parameter is not uber, then do not use a token. -> Afterward, how can I specify uber as a parameter in the custo ...

Why do I keep encountering the error "global is not defined" when using Angular with amazon-cognito-identity-js?

To start, run these commands in the command line: ng new sandbox cd .\sandbox\ ng serve Now, navigate to http://localhost:4200/. The application should be up and running. npm install --save amazon-cognito-identity-js In the file \src&bso ...

Utilize the gsap ScrollTrigger in conjunction with React's useRef() and Typescript, encountering issues with type mism

Recently, I've been trying to add some animation to a simple React Component using the GreenSock ScrollTrigger plugin. However, I ran into an issue due to types mismatch in my Typescript project. Here's a snippet of the code: import React, {useRe ...

Issues with code functionality following subscription via a POST request

I'm currently facing an issue with a service that utilizes an HTTP post request to communicate with the database. Unfortunately, when I try to implement this in my .ts file, nothing seems to happen after subscribing to the post. The post itself works ...

Issue encountered when attempting to import a module within the ionic framework

I encountered an issue in my project (built with the ionic-framework 3) where I included the following line to import the dialogflow module: const dialogflow = require('dialogflow'); However, when compiling, it resulted in the error message: ...

Using React to implement MUI autocomplete feature alongside a MUI form

Recently, I have been utilizing a MUI form structured in the following manner: <Box component="form" onSubmit={event => { return handleSubmit(event); }} noValidate sx={{mt: 1}}> <TextField margin="normal" ...

Using Angular 2 to inject JSON data through HTTP requests

http://localhost:3000/userinfo [ { "username": "simon", "password": "password1" }, { "username": "bala", "password": "password2" }, { "username": "prabha", "password": "password3" } ] myservice.service.ts import { Inje ...

CSS Styles not being applied globally in Angular

I've been struggling to properly set the Bootstrap downloaded css styles for my Angular project, despite following some instructions provided here: The styles were downloaded from: https://i.sstatic.net/g0kGH.png Initially, I was expecting it to re ...

Creating a Docker image for an Angular application with Node.js

Currently, I am attempting to develop an Angular application within a Docker environment and then run it as a container locally using Node.js. I have utilized the following Dockerfile to build the image, however, I am unsure of what might be missing when ...

Display the current date in YYYY/MM/DD format using a single method in React and TypeScript

Is there a better way to retrieve YYYY/MM/DD data using just one method? I attempted the following: date = created_at // from API const sendDate = `${String((date.getMonth() + 1)).padStart(2, '0')}${String(date.getDate()).padStart(2, '0&apos ...

The unit tests are not triggering the execution of setTimeout

Currently, I am developing a project in TypeScript and for unit-tests, I am utilizing QUnit and sinonjs. One of the functions within my code dynamically renders UI elements. I need to retrieve the width of these dynamic elements in order to perform additio ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

After upgrading from Angular 7 to 12, the module './rest.service.interface' does not export 'RestService' (imported as 'RestService'), causing it to not be found

Hey everyone, I've been struggling with a problem for hours now and I can't seem to fix it. Here is the interface I'm working with: import { HttpClient } from '@angular/common/http'; import { Response } from '@angular/http&apo ...