Using Angular: Inject a different function after unsubscribing from the Timer Observable

I'm currently developing an exam app and I'm facing an issue where the view controller is getting stuck in a loop after unsubscribing from the timer. The goal is to notify the user when their time is up and redirect them to a results page.

If anyone has any suggestions or solutions for this problem, please let me know!

Here's the code snippet:

minutesDisplay: number = 0;
hoursDisplay: number = 0;
secondsDisplay: number = 0;

sub: Subscription;

showAlert() {
    let alert = this.alertCtrl.create({

      subTitle: 'Ooops, Time Up! ',
    });
    alert.present();
    this.activity.openModal();
  }

ngOnInit() {
    this.startTimer();
}

public ngOnDestroy() {
    if (this.minutesDisplay == 1){
        this.sub.unsubscribe();
    }

    return true;

}

private startTimer() {
    let timer = Observable.timer(1, 1000);
    this.sub = timer.subscribe(
        t => {
            this.ticks = t;
            this.secondsDisplay = this.getSeconds(this.ticks);
            this.minutesDisplay = this.getMinutes(this.ticks);
            this.hoursDisplay = this.getHours(this.ticks);
            this.ngOnDestroy();
        }
    ); 
    this.showAlert();
 }

Answer №1

I haven't personally tested this solution, but you might want to consider the approach below:

function stopTimer() {
    this.timerSubscription.unsubscribe();  // Stop the timer if the user navigates away
}

function startCountdown() {
    let countdown = Observable.timer(1, 1000);
    this.timerSubscription = countdown.subscribe(
        count => {
            this.counter = count;
            this.seconds = this.getRemainingSeconds(this.counter);
            this.minutes = this.getRemainingMinutes(this.counter);
            this.hours = this.getRemainingHours(this.counter);
            if (this.minutes === 1) {
               this.timerSubscription.unsubscribe();  // Stop the timer when time is up.
               this.displayAlert();                     // Display alert at countdown completion
            }
        }
    ); 
}

Answer №2

Using the Observable.timer function, we create a timer that emits a tick every second. We then map each tick to check if the minutes are equal to 1. If they are, we take the first tick where this condition is true and subscribe to show an alert.

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 specialized type that guarantees a string union includes a particular string literal

I need to define a Mapped type that specifies a field named status which can be either a string or the string value ready: This example works as expected: export type ValidServiceState = HasReady<{ status: "ready" }>; The following should ...

Which to choose, setInterval or rxjs interval?

Many discussions have taken place on this topic, but I am still unsure about which approach is best for my specific use case. I have a method that needs to be called every 3 seconds in order to receive updated stock details. ngOnInit() { this.getUpdat ...

How can we determine the props' type specific to each component?

type ComponentCProps = { c: string; }; function ComponentC(props: ComponentCProps) { return <div>component C</div>; } type ComponentDProps = { d: string; }; function ComponentD(props: ComponentDProps) { return <div>component D& ...

Angular Material UI: Nested Table Component

I am dealing with a table that has four static headers and two static columns. The data in the last two columns changes based on certain conditions. I need to convert this table into an Angular Material table. The first table is a standard HTML table. Th ...

The document encountered an XMLHttpRequest error during the update process despite having CORS properly enabled

Encountering CORS errors when attempting to update a record: Cross origin requests are only supported for HTTP. XMLHttpRequest cannot load localhost:3000/api/adverts/5bf2b76c38c88dd144e5d4c3 due to access control checks. In create.component.ts: Handlin ...

What is the best way to determine the return type of a function based on the return type of its callback?

In the code snippet below, we have an interface that defines a function which takes a callback function and returns the value returned by the callback. export interface MonitoredOperation { <T = any>(operationName: string, operation: () => T ...

Encountering an Issue: Unable to connect with 'ngModel' as it is not recognized as a valid property for 'input' even after importing FormsModule

Despite importing FormsModule in my app.module.ts, I am still encountering the following error message. 'Cannot bind to 'ngModel' since it isn't a known property of 'input' I have thoroughly reviewed similar posts, but unf ...

The error message "Error: Unable to access property '_router' when null in NativeScript"

Currently, I am developing an android application using a combination of NativeScript, AngularJS2, and TypeScript. To guide my development process, I have been following the documentation provided by NativeScript, which can be found at this link. However, ...

Tips for including type definitions when adding elements to an array in TypeScript

Having trouble avoiding the use of 'any' as the type definition when pushing elements into an array? I attempted to specify the type but encountered an error. Here is a snippet of the code: interface answerProps { state: string; answer: s ...

The raw password value must be provided and cannot be left blank

I am currently learning Java Springboot and working on creating a todo app with React (TypeScript) and Springboot. As I attempt to signup, an error occurs stating "rawPassword cannot be null" from Springboot. My frontend is running on localhost:3000 and b ...

Are there challenges and ways to handle errors with React Hook Form in Typescript?

Transitioning to React Hook Form from Formik while incorporating Material UI V5 and yup for validation poses a current challenge. There are two key issues I am addressing: Encountering TS Errors related to various RHF props and options. Desiring validati ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

Getting an undefined value for a dynamic directive attribute in Angular5

I am utilizing "@angular/core": "^5.0.1", "@angular/material": "^5.0.0-rc.1", "@angular/cdk": "^5.0.0-rc.1". In my code, I am checking for the presence of a XXXqaName attribute in all fields, so I created a directive with an @input attribute that accepts ...

How can I implement email authentication in Angular using Firebase?

After only a month of playing around with Angular, I have managed to develop a web app with login and signup forms using Firebase for data storage and authentication. Typically, new users are required to sign up before logging in. However, I now face a di ...

Having trouble with the yAxis in HighCharts on Angular 8? FireFox and IE causing issues?

Hey there! Currently, I am using "highcharts 8.0.0" along with "highcharts-angular 2.4.0" in combination with Angular 8. While the line charts are displaying perfectly fine on Google Chrome, I seem to be facing an issue with Firefox. The problem is that t ...

Oops! An error occurred: Uncaught promise in TypeError - Unable to map property 'map' as it is undefined

Encountering an error specifically when attempting to return a value from the catch block. Wondering if there is a mistake in the approach. Why is it not possible to return an observable from catch? .ts getMyTopic() { return this.topicSer.getMyTopi ...

Switch the class of the Parent Component to that of the Child Component

Dashboard.html <nav #nav> <div class="nav nav-tabs" id="nav-tab" role="tablist"> <button class="nav-link active" id="nav-categories-tab" data-bs-toggle="tab" data-bs-targ ...

Defining types for functions that retrieve values with a specified default

My method aims to fetch a value asynchronously and return it, providing a default value if the value does not exist. async get(key: string, def_value?: any): Promise<any> { const v = await redisInstance.get(key); return v ? v : def_value; } W ...

Troubleshooting: Angular 6 issue - Unable to toggle visibility using ngIf

I am currently learning Angular and I'm working on the app.component.html as shown below: <app-login *ngIf="!loggedIn"></app-login> <section *ngIf="loggedIn" style="background:#EBF0F5;"> <div class="container"> ...

The Angular build is unsuccessful due to the presence of components from a separate Angular project

Whenever I execute ng build project1 --prod, the build fails and displays this error message: ERROR in : Cannot determine the module for class MyComponent in .../project2/app/my.component.ts! Add MyComponent to the NgModule to fix it.. Although the sol ...