我发现了一些非常好的观察结果.
只有顶层的信号读取才会触发该效果,不确定是否是设计的.
该效果返回一个引用,并具有 destruct 属性来 destruct 该效果并确保信号只运行一次!
完整代码:完整代码:
import { Component, effect, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
template: `
<button (click)="areAllDetailsLoaded.set(true)">areAllDetailsLoaded set true</button>
`,
})
export class App {
areAllDetailsLoaded = signal(false);
storage = signal(false);
name = 'Angular';
constructor() {
const effectRef = effect(() => {
console.log('effect runs');
// const storage1 = this.storage(); // un comment this to see the effect running for each change of storage
if (this.areAllDetailsLoaded()) {
const storage = this.storage();
console.log('code runs');
effectRef?.destroy();
}
});
}
ngOnInit() {
setInterval(() => {
this.storage.set(!this.storage());
console.log('interval', this.storage());
}, 1000);
}
}
bootstrapApplication(App);
Stackblitz Demo