Identifying a specific value of a variable in Typescript

I am currently developing an idle timeout feature for my application. Once the system detects inactivity, a modal window is triggered. Within this modal window, a timer is presented to the user. My goal is to have a way to determine when this timer reaches 0, so I can proceed with signing off the user accordingly.

export class IdleModalComponent implements OnInit {

counter$: Observable<number>;   
count = 300 // Here we set a countdown of 5 minutes before implementing the inactivity logic

constructor(public dialogRef: MatDialogRef<IdleModalComponent>) {
        this.counter$ = timer(0, 1000).pipe(
        take(this.count), 
        map(() => (--this.count)), 
    );
  }
}

By binding the counter observable in the HTML, the countdown is accurately displayed. The key requirement now is to identify:

this.count === 0.

Answer №1

To utilize the tap operator from RxJS library without the need for explicit subscription, you can implement it in the code snippet below:

this.counter$ = timer(0, 1000).pipe(
  take(this.count),
  map(() => (--this.count)),
  tap(val => {
    if (val === 0) {
      // Perform desired action like displaying a modal
      alert('The count is 0');
    }
  })
)

View Live Demo on StackBlitz

Answer №2

A timer that emits numbers in sequence at a specified duration.

When using the map function, avoid causing any side effects and simply map the received value.

To observe the completion:

  • Subscribe to the observable
  • Include a complete callback function
const startingNumber = 10;

timer(0, 100)
  .pipe(
    take(startingNumber),
    map(value => startingNumber - value))
  .subscribe({
    next: result => console.log(result),
    complete: () => console.log('Process completed')
  });


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

Tips for obtaining the iframe #document with cheeriojs?

I've been struggling to scrape the anime videos page [jkanime], specifically with extracting the mp4 video formats embedded in an iframe #document. Despite trying to use cheerio for querying, I've only managed to retrieve src links from Facebook ...

Angular build process encountering environment issue

When attempting to construct an Angular project, I am encountering the following problem: The file '/angular/src/environments/environment.ts' is not recognized as a module I am importing the file in this manner : import { environment } from ...

Transfer the value of a form field within the current object

I'm facing an issue when trying to pass a value to a personalized form validator: this.myForm = this.fb.group({ Id: [null], Password: ['', [Validators.required]], PasswordConfirm: ['', Validator ...

Ensure the most recently expanded item appears at the top of the TreeView by updating to Mui version

I'm working on a feature where I want to scroll the expanded TreeItem to the top when it has children and is clicked on for expansion. Any suggestions on how to make this happen? ...

Tips on customizing the selected icon color in Material-UI's BottomNavigationAction styling

I'm facing an issue with Material-UI styled components and could use some assistance. My goal is to create a BottomNavigation bar in React using Material-UI v5 where the selected option's icon displays in red (#f00) while the unselected icons sho ...

What can be used in place of Subject.prototype.hasObservers?

I have recently come across the version 4 of RxJS, and noticed that the method hasObservers on Subjects seems to have been removed. I am now faced with the challenge of migrating, as this removal is not documented on the migration guide. hasObservers: fun ...

Can dynamic attributes be used with ternary operators in Angular?

I attempted to alter the id of a div using Angular and implemented the following code: <div [id]="'item_' + (itemName !== undefined ? itemName.replace(' ', '-').toLowerCase() : '')"> However, when I run my te ...

Trouble Downloading CSV with Japanese Characters from Backend in Angular 9

I am trying to accomplish the following: when a user clicks on a download link, a CSV file containing Japanese characters should be generated dynamically from a Laravel backend and automatically downloaded to the user's PC. Issue: The CSV file displa ...

What is the best way to test a local variable in Angular 2 using karma and jasmine?

I've been working on writing a unit test with jasmine, but I've run into an issue when trying to test a local variable using jasmine. I have successfully tested a global variable in the past, but testing a local variable seems to be more challeng ...

How to set return types when converting an Array to a dynamic key Object in Typescript?

Can you guide me on defining the return type for this function? function mapArrayToObjByKeys(range: [string, string], keys: { start: string; end: string }) { return { [keys.start]: range[0], [keys.end]: range[1] } } For instance: mapArrayToObj ...

Understanding how to extract a specific value key from a JSON object in Typescript while utilizing Angular can greatly

I'm currently facing a challenge in Typescript with Angular where I need to retrieve a specific value from a JSON constant. While I am aware of the performance implications, I am wondering if there is a more efficient way to access this value within t ...

Guide to setting up a Mock Authentication Service for testing in Angular 6 using Jasmine

I am currently working on implementing a mock AuthService for my Angular 6 Jasmine component test. I am facing some difficulties in configuring it properly to "sign in" and utilize my MockAuthService effectively. What specific configurations am I overlook ...

Facing a problem with running npm start on jHipster

I am currently working on a jhipster project on my MacBook Pro running macOS Mojave v.10.14.4. After successfully compiling with npm start, the code continues to compile multiple times without any changes. Eventually, it throws the following error: DONE ...

Guide on displaying the length of an observable array in an Angular 2 template

I am working with an observable of type 'ICase' which retrieves data from a JSON file through a method in the service file. The template-service.ts file contains the following code: private _caseUrl = 'api/cases.json'; getCases(): Obs ...

When accessing from the frontend (Angular), the User.FindFirst(ClaimTypes.NameIdentifier) method does not return any values

I'm encountering a new issue - just as the title suggests. I've managed to identify where the problem occurs but I'm unable to resolve it. Let's start from the beginning. In the backend (ASP.NET 3.0), I have a class AuthController with ...

What is the best way to simulate the behavior of a function that is being called by a service during testing

Currently, I am developing a NestJS project and the task at hand involves writing unit tests for my services. One of the services in question is the BigQueryService, which utilizes @google-cloud/bigquery to interact with a Big Query dataset and execute qu ...

Discovering the Object with the Lowest Key Value in Typescript

Within my TypeScript code, I have defined a List as myList: Package[]. The structure of the Package model is outlined below - export class Package { ID: Number; Price: Number; } I am trying to retrieve a Package object with the lowest Price value using ...

Broadcasting events across the entire system

I'm trying to accomplish something specific in Angular2 - emitting a custom event globally and having multiple components listen to it, not just following the parent-child pattern. Within my event source component, I have: export class EventSourceCo ...

How to test Angular HttpClient in protractor end-to-end testing

Upon loading my application, an http call is made to the backend which causes my e2e test to fail in CI pipelines where no backend is available. I attempted to handle the error using the rxjs catchError operator on the http call. Additionally, I tried wr ...

The child component displays an error when input is entered, but occasionally it successfully loads

Currently, I am encountering an issue with passing an object from a parent component to a child component in Angular. Whenever I run the command ng serve, an error is thrown stating that the passed object cannot be found. However, on occasions when I save ...