Estou brincando com RxJS e Angular 19.1 e me deparo com um comportamento muito estranho:
intervalo.componente.ts
export class IntervalComponent {
count: string[] = [];
constructor (private cdr: ChangeDetectorRef) {
const secondsCounter = interval(1000);
const subscription = secondsCounter.subscribe (n => {
this.count = [...this.count, `It's been ${n} seconds since subscribing!`]
// I cannot understand why I need to trigger a change detection here as I am changing the value by reference.
// Either way, if I don't any change gets detected and both the `@for` and the `| json` pipe stays empty.
this.cdr.detectChanges();
if (n === 10) subscription.unsubscribe();
});
}
}
intervalo.componente.html
<h1>Intervals</h1>
<ul>
@for (c of count; track c) {
<li>{{ c }}</li>
<!-- Here it's supposed to add one value per second, but all of them are displayed from the beginning as if they were already loaded. -->
}
</ul>
{{ count | json}}
<!-- That's why I added this line, to check what was happening. -->
<!-- Here, all the values are displayed as they were supposed to, adding one by one every second. -->
Tudo super direto. No changeDetection é o padrão - JIC.
Eu sei que posso tentar com sinais, na verdade eu tentei. Então o detectChanges
não é necessário, mas o comportamento em .html
é o mesmo. Os valores em @for
são exibidos todos de uma vez.
Alguma ideia do porquê isso está acontecendo?