我正在使用 RxJS 和 Angular 19.1,遇到了一个非常奇怪的行为:
间隔.组件.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();
});
}
}
间隔.组件.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. -->
一切都非常简单。默认没有 changeDetection - JIC。
我知道我可以用信号试试,实际上我已经试过了。这样就detectChanges
不需要了,但中的行为.html
是一样的。上的值@for
会同时显示出来。
对于为什么会发生这种情况您有什么想法吗?