0

I am trying to get live data on angular basic component.

What I expect: HTML rendering auto incremented each 1 second (i.e.: 0, 1, 2, 3, 4, 5 ..etc.)

What I got: HTML rendering: 0 then 1. (incremented once then stopped)

Stackblitz url for demonstration (apologize if url not valid, first time sharing my code): https://stackblitz.com/edit/angular-9-starter-material-jdjcjp?file=src%2Fapp%2Fapp.component.ts

My code:

import {
  Component,
  OnInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
} from '@angular/core';
import { FormGroup, FormBuilder, FormArray } from '@angular/forms';
import { Observable, BehaviorSubject, combineLatest, timer } from 'rxjs';
import { map, tap } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AppComponent {
  constructor(private cdr: ChangeDetectorRef) {}

  item = 0;

  ngOnInit(): void {
    timer(1000)
      .pipe(
        tap(() => {
          this.item++;
          this.cdr.markForCheck();
        })
      )
      .subscribe();
  }
}
JustAG33K
  • 1,403
  • 3
  • 13
  • 28

2 Answers2

0

Use RxJs Interval instead of timer

interval(1000)  // emit every 1000 milliseconds
      .pipe(
        tap(() => {
          this.item++;
        })
      )
      .subscribe();
fujy
  • 5,168
  • 5
  • 31
  • 50
  • I used interval but not that way thx for help. – Ahmad Barutchi Aug 09 '22 at 00:39
  • @AhmadBarutchi, what you used is the window `setInterval()` method, this is different from RxJs `Interval` operator, please make sure that you understand the difference, and when to use which? https://stackoverflow.com/questions/69176940/setinterval-or-rxjs-interval-which-one-to-use – fujy Aug 09 '22 at 00:47
0

Found it:

ngOnInit() {
    return setInterval(() => {
          this.item++;
          this.cdr.markForCheck();
    }, 1000);
}
vimuth
  • 5,064
  • 33
  • 79
  • 116