Run a function from an alternate element

I have successfully created a grid with a button that enables me to control a timer.

When I click on the start button in the grid on the home page, the timer begins counting the time.

By using a service, I am able to determine whether the timer is active or not, and change the status of the button on the navbar component accordingly.

My question is: How can I pause the timer (execute the pauseTimer function) from the home service/component, but trigger it from the navbar component? Essentially, I want to be able to pause a timer that was started on the home page by clicking the stop button on the navbar component.

Any assistance would be greatly appreciated!

DEMO

UPDATED CODE:

  startTimer(userId:string) {
    if (!this.timerForUsers[userId]) {
      this.timerForUsers = {
        ...this.timerForUsers,
        [userId]: {
          currentState: 'start',
          currentTime: 0,
          initialTime: 0,
          startTime: `${Date.now()}`
        }
      };
    }

    const currentUserTimer:TimerForUser = this.timerForUsers[userId];
    clearInterval(currentUserTimer.interval);
    currentUserTimer.startTime = `${Date.now()}`;
    currentUserTimer.initialTime = currentUserTimer.currentTime;

    currentUserTimer.interval = setInterval(() => {
      this.timerForUsers = {
        ...this.timerForUsers,
        [userId]: {
          ...this.timerForUsers[userId],
          currentTime: this.timerForUsers[userId].currentTime + 1 
        }
      };
    }, 1000);

    this.userID = userId;
    currentUserTimer.currentState = 'start';
     this.state = currentUserTimer.currentState;


    localStorage.setItem('user_timers', JSON.stringify(this.timerForUsers));
  }

  pauseTimer(userId:string) {
    const currentUserTimer:TimerForUser = this.timerForUsers[userId];

    currentUserTimer.currentState = 'pause';
    this.state = currentUserTimer.currentState;
    clearInterval(currentUserTimer.interval);
    currentUserTimer.interval = null;
    currentUserTimer.initialTime = currentUserTimer.currentTime;
    currentUserTimer.startTime = null;
    localStorage.setItem('user_timers', JSON.stringify(this.timerForUsers));
    currentUserTimer.currentTime = null;
  }

     gettimes() {
    return this.userID;
  }

    getCurrentState() {
    return this.state;
  }

Answer №1

If I understand correctly, you would like to halt the timer and update the button in the navigation bar component. Feel free to check out the demo for reference. I hope this information proves helpful.

I've made some modifications:

public timerAction:ReplaySubject<any> = new ReplaySubject(1);
to the TaskService

and in the HomeComponent

pauseTimer(data) {
     this.taskService.iduser = data.key.ID;
    this.taskService.pauseTimer(data.key.ID);
    this.taskService.timerAction.next(true);// included this
  }
in NavbarComponent

constructor(public taskService: TaskService) { 
    this.taskService.currentUserId.subscribe(x => {
      this.userId = x;
      this.startTimer();
    });
    
    // added this, a subscription that listens for changes and triggers pauseTimer if true.
    this.taskService.timerAction.subscribe(response =>{
      if(response)
        this.pauseTimer();
    })
  }

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

Implementing validation for a dynamic form

I'm currently working on a basic form that includes multiple questions with dropdown options as answers. Here's what I've managed to accomplish so far. I've successfully implemented a dynamic form where the data loads correctly into t ...

Synchronizing data between parent and child components using two-way binding with emit in Vue 3 using TypeScript

Within my code, there is a child component: <template> <label :class="className + ' ctrl'"> <span><LocCtrl :page="pageName" :locKey="labelLoc" /></span> <input type=&q ...

Creating mock objects with Jest

I am currently delving into the world of jest testing. Here is a snippet from an implementation class I'm working with: import { ExternalObject } from 'external-library'; export class MyClass { public createInstance(settings : ISettings) ...

Validate if the program is currently running as "ionic serve" before implementing a conditional statement

Is there a method to determine if the ionic serve CLI is currently active (indicating it's not running on a physical device) within the code and use it as a condition? My problem: I have a Cordova plugin that returns a response to Cordova. When usin ...

Utilizing Min and Max Validation in Angular 2 Template-Driven Forms

I attempted to incorporate min validation in a template form, but unfortunately it did not function as expected. Could someone provide guidance on how to properly use it in a template form? Thank you in advance for your assistance. <input type= ...

What is the best technique for verifying the existence of data in the database before making updates or additions with Angular's observables?

I am facing a straightforward issue that I need help with in terms of using observables effectively. My goal is to search my database for a specific property value, and if it exists, update it with new data. If it does not exist, then I want to add the new ...

Eliminate text from template literals in TypeScript types

I have successfully created a function that eliminates the 'Bar' at the end of a string when using foo. However, is there a way to achieve the same result using the type statement? (refer to the code snippet below) declare function foo<T exten ...

Verify if the Observable (HTTP request) has provided a response, and if not, hold for it?

In my Angular app, I have a calendarComponent that fetches entries from a MongoDB through firebase cloud functions using the calendarService. When creating a new entry, I display an addEventComponent dialog which requires data from the database to function ...

Sending array values from a dynamic input field in Angular 4 and processing them accordingly

I am currently exploring options on how to add and delete multiple input fields. When a user submits two or more fields, I want the results to be displayed in an array. This is my HTML form: <form method="post" [formGroup]="formData"> ...

Creating a unique custom complex template typeahead implementation with Angular 2 and Ng2-Bootstrap

I encountered an issue with the ng2-bootstrap typeahead implementation and have created a plunker to demonstrate the problem. Check out the plunker example here <template #customItemTemplate let-model="item" let-index="index"> <h5>This is ...

Simplifying imports in Angular, the easy way: A guide to stream

We recently made a change to our Angular project by moving the npm-library @ng-plus/modal to live as a project library under the project/ngplus-modal folder. One issue we encountered is with the imports within the project. Even though we previously def ...

Choose between creating an observable pipe within a function or storing it in a variable

Currently, I have a functional code snippet that leverages the Angular service to create an Observable pipeline. This pipeline utilizes operators like mergeMap, filter, map, and shareReplay(1) to manage user authentication and fetch the onboarding status f ...

The CSS for SVG circles breaks in Firefox, causing the browser to strip away the radius property

Currently, I am working on creating a progress ring using SVG and CSS. It is functioning well in Chrome; however, Firefox (61.0.1 (64-bit)) is giving me trouble as it does not display the circle. I attempted to apply the method from this question but did n ...

Typescript - Specifying the return type for a deeply nested object

I have a container that holds multiple sub-containers, each containing key-value pairs where the value is a URL. I also have a function that takes the name of one of the sub-containers as input, loops through its entries, fetches data from the URLs, and re ...

Updating displayed content based on orientation switch

Two components, A and B, are displayed simultaneously - A on the left and B on the right - when the device is in landscape mode. In portrait mode, either A or B will be displayed based on user selection. The components can transition from A to B and vice v ...

Display HTML tags on an HTML page using TypeScript

In my angular application, I encountered an issue where I needed to call one component inside another component. Initially, I was able to achieve this by simply using the second component's selector in the HTML of the first component: html: <div&g ...

Function in nodejs throwing an error: Return type missing

I am facing an issue with this code snippet while trying to compile the application. public async test(options?: { engine?: Config }): Promise<any> { const hostel = new Service({ list: this.servicesList, createService ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Detecting changes in a readonly input in Angular 4

Here is a code snippet where I have a readonly input field. I am attempting to change the value of this readonly input from a TypeScript file, however, I am encountering difficulty in detecting any changes from any function. See the example below: <inp ...

Emitter fails to emit the value

I've been working on a filter component that looks like this: <app-filter (newStatusValue)="changeListByStatus($status)" However, I'm running into an issue where nothing is being output... changeListByStatus($status){ console.log('ch ...