The dreaded glitch in Angular's setInterval function

My goal is to implement polling for a single page and disable it when the user navigates away from that page. However, I encountered an error during the build process when I attempted to set up the polling interval using setInterval:

error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Below is the code for the CommandPageComponent class:

export class CommandPageComponent implements OnInit, OnDestroy {

  private lastUpdate: number;
  private timer: any;
  private pollingTimer: any;
  private seconds = 0;

  constructor(private router: Router, private consultService: ConsultService, private configService: ConfigService) {

    this.configService.getConfigData('pollingEnabled').subscribe(enabled => {
      if (enabled) {
        let j = 0;
        this.configService.getConfigData('pollingInterval').subscribe(interval => {
          this.pollingTimer = setInterval(() => {
            console.log('polling', ++j);
            console.log('polling', interval);
            this.seconds = 0;
            this.consultService.sendConsultPollingRequest();
          }, interval * 1000);
          this.timer = setInterval(() => {
            this.lastUpdate = interval - this.seconds++;
          }, 1000);
        });
      }else {
        console.log('Polling disabled');
      }
    });
  }


  ngOnDestroy() {
    // Will clear when component is destroyed e.g. route is navigated away from
    if (this.pollingTimer) {
      clearInterval(this.pollingTimer);
    }
    if (this.timer) {
      clearInterval(this.timer);
    }
    console.log('Clear polling');
  }

}

Can anyone help identify where the issue might be occurring? Thank you.

Answer №1

The problem is quite obvious :

this.configService.retrieveData('pollingDuration').subscribe(duration => {

The value of duration is not being retrieved as a number, because of this reason, these two lines

duration * 1000

this.lastTimeUpdated = duration - this.count++;

are causing the following error:

Error TS2362: The left-hand side of a mathematical operation must be of type 'any', 'number', or an enum type.

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

Unable to submit form data in AWS Amplify & React: The message "Not Authorized to access createRecipe on type Mutation" is displaying

I've recently set up a project using React and AWS Amplify. I've successfully added some data to DynamoDB in AWS, but when I try to submit form data from my React App, I encounter an error from the API. I'm a bit stuck on what to do next. I ...

What could be causing the type errors I am encountering while trying to resolve this Promise within a generic function?

I am attempting to implement additional types within this WebSocket protocol: type Action = { action: "change-or-create-state"; response: string; } | { action: "get-state"; response: string | null; }; /** * map an action to its response ...

Warnings when compiling Angular with declarations of Angular Material components

Recently, I've been encountering numerous warnings during compilation after installing Angular Material. The warnings persist whether I install it directly from npm or through ng add @angular/material, regardless of whether I opt to use animations or ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

Contrast between utilizing filter_input and accessing $_POST directly following an asynchronous AJAX request

When I use filter_input(INPUT_POST, 'attribute') and $_POST['attribute'], I get different results and I can't figure out why. The Post-Request is sent by a JavaScript script built with JQuery and it looks like this: // type javaS ...

What is the best way to alter the Date format in Typescript?

Within my response, the field createdate: "2019-04-19T15:47:48.000+0000" is of type Date. I am looking to display it in my grid with a different format such as createdate: "19/04/2019, 18:47:48" while maintaining its original data type. To achieve this, I ...

Panning or dragging on Google Map V3 can become unresponsive when the cursor moves outside of the map element

I have incorporated a Google map in a specific section of my webpage. I am facing an issue where if I click and drag the mouse outside the map area to other div elements, releasing the mouse still causes dragging/panning to continue when I return to the m ...

The html-duration-picker is not being displayed in the proper format

I've been working on integrating an external library that allows for inputting document length. Specifically, I'm using the html-duration-picker library, but it seems like the input functionality is not quite right for durations. Could it be th ...

Updating parameter value upon the execution of an internal function in Javascript

How can I log the text from a textbox to the console when a button is clicked in this code snippet? <body> <input type="text" id="ttb_text" /> <script type="text/javascript"> function AppendButton() { var _text = ''; ...

Is there a way in Vue.js for me to access a method from within the same component using the component's data?

Below is the code for a specific component: <template> <li v-for="(item, i) in this.menu" :key="i" @click="item.action()"> //attempting to call the method in the component {{menu.title}} <li> </template> <script> ...

Is there a translation issue affecting Chrome version 44?

Recently, Chrome 44 (44.0.2403.89 m) was released and I've encountered some issues with the translate3d feature (on both Mac and Windows versions). This problem is impacting plugins such as fullPage.js and consequently affecting numerous pages at th ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Attempting to implement ajax for form submission, however finding that the $_POST array is coming back as empty

I'm attempting to send JavaScript arrays to a new page using Ajax. Although there are numerous questions on this topic on Stack Overflow, I have decided to implement Ajax in the following manner after examining various answers: var test = {}; test[& ...

Exploring Scope Data Using a Custom AngularJS Directive

We are completely new to the world of AngularJS and are currently facing a challenge in displaying HTML tooltips from a custom directive within Angular. As beginners in this technology, we are struggling to find the right solution for this issue. Initiall ...

The jQuery script is malfunctioning

I have implemented an order form where users must complete a captcha code verification for cash on delivery. I am using jQuery to validate the entered captcha code. If the entered captcha code is incorrect, I prevent the user from submitting the form and ...

Error message in Angular 5: $any does not work as a function

I've encountered an issue with Angular 5 that keeps popping up in various projects while using VS Code. The error I see in Chrome Dev Tools is: ERROR TypeError: jit_nodeValue_6(...).$any is not a function One specific instance where the problem a ...

Is it possible to duplicate a div element and then make changes to both the original and the clone using a single button

I am dealing with an element that has three sub-elements element1, element2, and element3. When I press the button1 command, it filters element1. When I press the button2 command, it filters element2. How can I clone this element and manipulate both th ...

No routes found that match. URL Segment 'calendar' does not correspond to any routes available

Currently interning, I've been tasked with building my own Angular 5 web application. However, I've hit a roadblock with an issue that's had me stuck for hours now. Every time I try to access the calendar, it gives me an error saying it can& ...

Can an array in Javascript contain another array?

I am looking to organize multiple sets of information, each containing specific details. This is how I envision it: var users = [{userID:1, userName:robert}, {userID:2, userName:daniel}] Then, when I want to access this data: users.userID // 1, 2 users. ...

Utilizing JQUERY and AJAX for conditional statements

I am currently in the process of creating a basic chat bot. At this point, the bot replies when the user inputs a pre-defined question. However, I am trying to figure out how to program the chatbot to respond with a "sorry, I don't understand" message ...