Resetting the timer of an observable in Angular 2

I have a unique service that automatically calls a method every 30 seconds. There is also a button that allows the user to reset the timer, preventing the method from being called for another 30 seconds. How can I make sure that the method does not get called within the interval if the button is clicked?

COMPONENT

constructor(private customService: CustomService) {
  this.customService.initiate();
}

resetTimer(): void {
  this.customService.resetTimer();
}

SERVICE

initiate(): void {
    timer(0, 30000).subscribe(() => this.refresh());
}

resetTimer(): void {
  // Need guidance here
}

Currently, my component initializes the timer by calling the initiate() method in its constructor. The idea is that by calling resetTimer() in the component's HTML, it will eventually call the resetTimer() method in the service to restart the timer. Can you assist me with achieving this functionality?

Appreciate your help!

Answer №1

To achieve this functionality, I recommend utilizing the switchMap operator, which will unsubscribe from the previous timer and subscribe to a new one that starts from the beginning.

private reset$ = new Subject();

initialize(): void {
  this.reset$
    .pipe(
      startWith(void 0),
      switchMap(() => timer(0, 30000)),
    )
    .subscribe(() => this.refresh());
}

refreshTimer(): void {
  this.reset$.next(void 0);
}

It is important to note that the startWith operator is necessary in order to trigger the creation of the initial timer upon subscription.

Answer №2

To reset the timer observable, it is recommended to first unsubscribe and then resubscribe.

t = timer(0, 30000);
sub: Subscription;

initialize(): void {
    this.sub = this.t.subscribe(() => this.refresh());
}

refreshTimer(): void {
    this.sub.unsubscribe();
    this.initialize();
}

Alternatively, you can combine both actions into one method:

t = timer(0, 30000);
sub: Subscription;

initTimer(): void {
    this.sub && this.sub.unsubscribe();
    this.sub = this.t.subscribe(() => this.refresh());
}

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

Attempting to eliminate any dates that have already occurred

I am faced with an array containing various dates in string format such as "2016-08-12". My goal is to eliminate any dates that have already passed by comparing them to today's date. I am using TypeScript for this task. Here is a snippet of my datoAr ...

Using Angular 4 to import an HTML file

I am trying to save test.svg in a component variable 'a' or svgicon.component.html. To achieve this, I have created the svgicon.component.ts file. However, it's not working. What steps should I take next? svgicon.component.ts import ...

TypeScript PatchBaseline with AWS CDK

I am currently working with the AWS CDK and TypeScript, utilizing the @aws-cdk/aws-ssm library to create a PatchBaseline. While I have successfully created the Patch baseline, I'm encountering difficulties when attempting to define approvalRules. I ca ...

What is causing the issue where search query parameters are not recognizing the initially selected option?

Hey, I'm having an issue with searchParams. The problem is that when I apply filters like "Breakfast, Lunch, Dinner", the first chosen option isn't showing up in the URL bar. For example, if I choose breakfast nothing happens, but if I choose lun ...

Adding items to the array is only effective when done within the loop

My approach involves retrieving data from an API using axios, organizing it within a function named "RefractorData()," and then pushing it onto an existing array. However, I have encountered a problem where the array gets populated within a forEach loop, a ...

Transform an Angular 2 application to seamlessly incorporate an SDK

I have been working on an Angular 2 application and I am curious if it is feasible to transform this into an SDK that can be easily integrated into other applications by simply adding script tags in their headers. If this conversion is not achievable, co ...

Dealing with asynchronous data in ngOnInit in Angular 4 when routing with parameters: tips and tricks

I'm currently facing an issue with loading data from my web api controller. The problem lies in the fact that I am using my API service, which is invoked from the ngOnInit function of the component. However, the view remains empty as the data retrieva ...

The parseFloat function only considers numbers before the decimal point and disregards

I need my function to properly format a number or string into a decimal number with X amount of digits after the decimal point. The issue I'm facing is that when I pass 3.0004 to my function, it returns 3. After reviewing the documentation, I realized ...

When triggering the event: Was anticipating a spy, however received a Function instead

Upon running my test, I encountered the following error message: Error: Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but received Function. it('should change the value of myComponent', () => { spyOn(component ...

Spring OAuth2 preflight responds with a 302 status code

I have implemented OAuth2 in my Spring application with a resource server and authentication server. I am attempting to send a GET request to the resource server from Angular2, but I am receiving a 302 response for the OPTIONS request. Unfortunately, I do ...

When an import is included, a Typescript self-executing function will fail to run

Looking at this Typescript code: (()=> { console.log('called boot'); // 'called boot' })(); The resulting JavaScript is: (function () { console.log('called boot'); })(); define("StockMarketService", ["require", "exp ...

Issue encountered during execution of tests involving reactive forms

Having some issues with the code below and looking for a solution. The tests pass when mocking the form for ts tests, but encounter an error when mocking the same form for html: No value accessor for form control with name: 'Enable' If I remov ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

Problem with Ionic2 star rating component

I am currently learning how to use rating stars in my Ionic2 app. I came across a helpful link on setting up rating stars in Ionic2. However, I encountered an issue when I tried to add the output tag. Can someone assist me with this problem? rating.html ...

Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "_id": "12123", "dateCreated": "2019-12-03T13:45:30.418Z", "pharmacy_id": "011E7523455533 ...

Exploring the integration of Angular framework with Laravel

Currently, I am coding in Laravel 7 and Angular 10 separately. However, for my upcoming project, I will be incorporating both Laravel and Angular together. My plan is to integrate Angular into my Laravel application and leverage Angular for my JavaScript t ...

How to incorporate a custom JavaScript file into an Angular 7 application

Suppose there is a JavaScript file named mylib.js in an angular 7 application, located at assets/mylib.js: mylib = function(){ return { hi: function() { alert('hi'); } }; }(); If I want to be able to call mylib.hi() in my hero-f ...

`The dilemma of z-index in a dropdown menu nested within an animated card`

Having an issue that I have attempted to simplify in this StackBlitz example (the actual project is created with Angular components and Bootstrap, etc.): https://stackblitz.com/edit/angular-bootstrap-4-starter-njixcw When incorporating a dropdown within ...

Unloading a dynamically-loaded child component in Vue.js from the keep-alive cache

I have a question that is similar to the one mentioned here: Vue.js - Destroy a cached component from keep alive I am working on creating a Tab System using Vue router, and my code looks something like this: //My Tab component <template> <tab& ...

Angular 2 does not recognize the element 'child-selector' as valid

In my quest to establish communication from a child component to a parent component based on certain actions, I have incorporated the use of both EventEmitter and Output libraries. Let me walk you through what I have achieved thus far. Firstly, let's ...