Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The SetInterval function does'nt work in Angular 17

When i use setInterval in Angular the browser doesnt load the content anymore. This problem just happens in Angular 17. I dont know if im the only one with this or if nobody in Google or in Angular community notice, that there is a problem with the setInterval.

import { AfterViewInit, Component, OnInit, inject } from '@angular/core';
import { CarService } from '../services/cars.service';
import { Car } from '../interfaces/car';

@Component({
  selector: 'app-count-cars',
  standalone: true,
  imports: [],
  templateUrl: './count-cars.component.html',
  styleUrl: './count-cars.component.scss'
})
export class CountCarsComponent implements AfterViewInit {
  carService: CarService = inject(CarService)
  cars: Car[] = []
  carsNumber = 0;
  constructor() {
    this.cars = this.carService.getCars();
    this.carsNumber = this.cars.length;
  }
  ngAfterViewInit(): void {
    setInterval(()=> {
      this.cars = this.carService.getCars();
      this.carsNumber = this.cars.length;
    }, 10000)
  }
}

Everything works well without setIntervall.

like image 488
Fotso Rostand Avatar asked Oct 15 '25 04:10

Fotso Rostand


1 Answers

Your builder is probably building a server-side bundle too which will get stuck if you use any setInterval without checking if the platform is a browser. The server run will infinitely run the interval and will not proceed.

Wrap your interval inside an if block with a condition to check that the platform is or is not a browser.

try this:

import { AfterViewInit, Component, OnInit, inject, LOCALE_ID } from '@angular/core'; // update this
import { CarService } from '../services/cars.service';
import { Car } from '../interfaces/car';
import {isPlatformBrowser} from "@angular/common"; // update this

@Component({
  selector: 'app-count-cars',
  standalone: true,
  imports: [],
  templateUrl: './count-cars.component.html',
  styleUrl: './count-cars.component.scss'
})
export class CountCarsComponent implements AfterViewInit {
  carService: CarService = inject(CarService)
  cars: Car[] = []
  carsNumber = 0;
  isBrowser = signal(false);  // a signal to store if platform is browser

  constructor(@Inject(PLATFORM_ID) platformId: object) {
    this.isBrowser.set(isPlatformBrowser(platformId));  // save isPlatformBrowser in signal
    this.cars = this.carService.getCars();
    this.carsNumber = this.cars.length;
  }
  ngAfterViewInit(): void {
    if(this.isBrowser()) { // check it where you want to write setTimeout or setInterval
      setInterval(()=> {
        this.cars = this.carService.getCars();
        this.carsNumber = this.cars.length;
      }, 10000)
    }
  }
}
like image 193
MahdiJoon Avatar answered Oct 17 '25 16:10

MahdiJoon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!