Angular v16中的信号和效果

huangapple go评论62阅读模式
英文:

Signals and effects in Angular v16

问题

我正在学习如何在最新的Angular中使用信号。具体来说,我卡在了Effects上。我看到可以通过以下方式创建一个Effect:

effect(() => console.log(this.value()));

但是,我怎么知道特定信号何时发生了变化?实际上,在一个组件中可能会有多个信号。

谢谢

英文:

I am learning how to use signals in the latest Angular. Specifically, I am stuck on Effects. I see that I can create an effect in that way:

effect(() => console.log(this.value()));

But how do I know when a particular signal is changed? In reality there will be more than one signal in a component.

Thanks

答案1

得分: 2

Effects仅在其内部的信号值发生更改时执行。考虑以下示例:

export class App {
  name = 'Angular';
  foo = signal('foo');
  bar = signal('bar');

  constructor() {
    effect(() => {
      console.log(this.foo());
    });

    effect(() => {
      console.log(this.bar());
    });

    effect(() => {
      console.log(this.foo(), this.bar());
    });
  }

  changeFoo() {
    this.foo.set('foo' + Math.random().toString());
  }

  changeBar() {
    this.bar.set('bar' + Math.random().toString());
  }
}

当调用changeFoo时,只有第一个和第三个效果会被调用,因为它们都引用了foo。第二个效果记录bar的值,但不会执行,因为它不引用foo

英文:

Effects are executed only when a value of a signal inside it is changed. Consider this example:

export class App {
  name = 'Angular';
  foo = signal('foo');
  bar = signal('bar');

  constructor() {
    effect(() => {
      console.log(this.foo());
    });

    effect(() => {
      console.log(this.bar());
    });

    effect(() => {
      console.log(this.foo(), this.bar());
    });
  }

  changeFoo() {
    this.foo.set('foo' + Math.random().toString());
  }

  changeBar() {
    this.bar.set('bar' + Math.random().toString());
  }
}

When changeFoo is called, only the first and the third effect will be called, because both of them are referencing foo. The second effect which logs value of bar won't be executed, as it doesn't reference foo.

答案2

得分: 0

效果始终至少运行一次。当一个效果运行时,它会追踪任何信号值的读取。每当这些信号值中的任何一个发生变化时,效果会再次运行。与计算信号类似,效果会动态地跟踪它们的依赖关系,并且只跟踪在最近的执行中读取的信号。

请参阅 https://angular.io/guide/signals#effects

英文:

Effects always run at least once. When an effect runs, it tracks any signal value reads. Whenever any of these signal values change, the effect runs again. Similar to computed signals, effects keep track of their dependencies dynamically, and only track signals which were read in the most recent execution.

See https://angular.io/guide/signals#effects

huangapple
  • 本文由 发表于 2023年6月29日 03:41:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576259.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定