Executing Timers in Angular 5 Service

I am working on implementing a property called currentAndLastVehicles in my service that needs to be updated automatically every second.

Here is what I have so far:

import { Injectable } from '@angular/core';

@Injectable()
export class SharedDataService {

  constructor() {
    setTimeout(() => {
      console.log("hello");
      this.currentAndLastVehicles = [(Math.floor(Math.random() * (1000000 - 9999999)) + 9999999).toString(), ...this.currentAndLastVehicles];
    }, 1000);
  }

  public currentAndLastVehicles: string[] = [];
}

Challenges I am facing:

  • The setTimeout function is only executed once, probably because it is inside the constructor.
  • Placing setTimeout outside of the constructor results in multiple errors.

Can anyone suggest a solution to achieve the desired functionality?

Answer №1

To keep a function running at certain intervals, utilize the setInterval method.

The function will continue to execute until you explicitly call clearInterval. To stop the interval, create a method in your service and invoke it within the ngOnDestroy lifecycle hook of the AppComponent.

Within your constructor, initialize a variable like this:

constructor(){
     this.intervalInstance = this.startInterval();
}

Your service should have a function defined as follows:

startInterval() {
   setInterval(()=>{
      this.dataArray = [(Math.floor(Math.random() * (1000000 - 9999999)) + 9999999).toString(),...this.dataArray];
},10000)

In the app component's ngOnDestroy method, call:

ngOnDestroy() {
  this.service.stopInterval()
}

In your service, define the following method:

stopInterval(){
  clearInterval(this.intervalInstance);
}

Answer №2

To achieve continuous execution every second, opt for the setInterval function instead of using setTimeout, which runs only once.

Answer №3

If you wish to continuously update your data every second, employing a reactive strategy can be effective.

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/interval';

@Injectable()
export class SharedDataService {
  poll$: Observable<any>;

  constructor() {
    this.poll$.interval(1000).subscribe(() => {
      return this.currentAndLastVehicles = [(Math.floor(Math.random() * (1000000 - 9999999)) + 9999999).toString(),...this.currentAndLastVehicles];
    }
  }

  public currentAndLastVehicles : string[] = [];
}

Answer №4

If you need a function to run every X seconds until it is canceled, you can utilize the setInterval method.

setInterval(() => {
      console.log("hello");
      this.currentAndLastVehicles = [(Math.floor(Math.random() * (1000000 - 9999999)) + 9999999).toString(),...this.currentAndLastVehicles];
    }, 1000);
 }

Remember to save the value returned by setInterval so that you have the option to cancel it when necessary.

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

Can you explain Angular's "rule of unidirectional data flow" to me?

The concept of Angular's "unidirectional data flow rule" is mentioned throughout various sections of the Angular documentation, yet a clear and concise definition of this rule is nowhere to be found. After thorough research, I discovered two somewhat ...

React Traffic Light Component: Colors Stuck After Timeout

I've been working on solving a React issue and followed a tutorial on YouTube. I'm using CodeSandbox for my project, but I'm facing a problem where the colors of the signal are not showing up and do not change after some time. I even tried u ...

How to Validate Ionic 2 Radio Button Selections with TypeScript

Imagine having a list like the one shown below: <ion-list radio-group [(ngModel)]="autoManufacturers"> <ion-list-header> Auto Manufacturers </ion-list-header> <ion-item> <ion-label>Cord</ion-label> &l ...

What is the best way to remove linear-gradient effects applied by a dark mode theme?

Why does MUI add random gradients to components, like in dark mode? Is there a way to disable this feature because it doesn't match the exact color I expected for my custom theme... My Theme Options export const themeOptions: ThemeOptions = { palette ...

Importing TypeScript modules dynamically can be achieved without the need for Promises

I find myself in a scenario where the dynamic nature of these commands is crucial to prevent excessive loading of unnecessary code when executing specific command-line tasks. if (diagnostics) { require('./lib/cli-commands/run-diagnostics').run ...

Steps for importing a CommonJS module that exports as a callable into TypeScript

I am dealing with a project that has a mixture of JavaScript and TypeScript files. Within the project, there is a JS library that follows this structure: module.exports = () => { // logic dependent on environment variables // then... return { ...

What is the TypeScript definition for the return type of a Reselect function in Redux?

Has anyone been able to specify the return type of the createSelector function in Redux's Reselect library? I didn't find any information on this in the official documentation: https://github.com/reduxjs/reselect#q-are-there-typescript-typings ...

TypeScript - creating a dynamic instance of a new class with a custom

Looking to dynamically create new class objects in a loop with customizable names? For example, having classes like "tree": export default class ParentClass { // ... } export default class Thomas extends ParentClass { // ... } export default cla ...

When utilizing WPF WebBrowser with a local Angular 8 website, the window.external feature works flawlessly. However, complications arise when

Apologies for any formatting issues, this is my first post. I have been working on updating a legacy app with a new UI. This serves as a proof of concept to demonstrate our ability to create a thin client and host our project online. In my WPF window (.NE ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

The InMemoryCache feature of Apollo quietly discards data associated with fragments that are declared on the main

After sending the following query to my GraphQL server: fragment B on root_query { foo { id } } query A { ...B } The data received from the server includes the foo field. However, when I retrieve it using Apollo's InMemoryCache a ...

Visualization of pie charts in Angular2 using Google library

Currently, I am in the process of building a web application using Angular2 that includes a Google pie chart. One of the components of the application is a Directive specifically designed for the pie chart. Below is the code snippet for the Directive: @D ...

Exploring the behavior of control flow in Typescript

I am a beginner when it comes to JS, TS, and Angular, and I have encountered an issue with an Angular component that I am working on: export class AdminProductsMenuComponent implements OnInit{ constructor(private productService: ProductService, ...

I encountered a SyntaxError while parsing JSON due to an absence of a number after a minus sign at position 1

I am trying to use the replicate model visoar/product-photo:edf42659dae0da88a26dba4912e7e4bb6c2fba25b1e1c6a5464cf220e467bce0, but when I provide it with an image and a prompt like on this page.tsx: "use client" import { LandingNavBar } from &apo ...

Acquiring user information from Firebase using Angular 2

Here's a signup code snippet that pertains to my previous inquiry on Stack Overflow about adding user data upon account creation. The code is as follows: signup(){ firebase.auth().createUserWithEmailAndPassword(useremail, userpassword) .then(fu ...

What is the best method for connecting a ref to a component that I am duplicating with React.cloneElement?

Hi everyone! I'm trying to pass a ref into my component so that I can access the variables on the component like state. The only problem is, I'm having trouble getting it to work. It needs to be functional for both classes and functions. Every t ...

Typescript defines types for parameters used in callbacks for an event bus

Encountering a TypeScript error with our custom event bus: TS2345: Argument of type 'unknown' is not assignable to parameter of type 'AccountInfo | undefined'. Type 'unknown The event bus utilizes unknown[] as an argument for ca ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

"Troubleshooting: The Angular Check-All feature is unexpectedly selecting disabled checkboxes within the ngx data

Within ngx-datatable, I have implemented a functionality where some checkboxes are disabled based on certain conditions. However, when I try to select all checkboxes, even the disabled ones get selected. How can this issue be resolved so that disabled chec ...

When incorporating leaflet-routing-machine with Angular 7, Nominatim seems to be inaccessible

Greetings! As a first-time user of the Leafletjs library with Angular 7 (TypeScript), I encountered an error while using Leaflet routing machine. Here is the code snippet that caused the issue. Any ideas on how to resolve this problem? component.ts : L. ...