Angular signal computed(() => toSignal()) throws Error

627 views Asked by At

Following code

  source$ = of(1);
  value = computed(() => toSignal(this.source$));

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

Throws ERROR Error: NG0602: toSignal() cannot be called from within a reactive context. Invoking toSignal causes new subscriptions every time. Consider moving toSignal outside of the reactive context and read the signal value where needed. Find more at https://angular.io/errors/NG0602

Why do I get this error? I know that I could just use the toSignal without computed then it works. However I want to make use of the computed-memoization.

When splitting it up in two steps it does not throw:

  source$ = of(1);
  v =  toSignal(this.source$);

  value = computed(() => this.v());

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

There are 1 answers

1
OZ_ On BEST ANSWER

computed() is not supposed to create new signals (inside the computation function), it should derive (in other words, "compute") the new value from values of one or multiple signals.

I know that I could just use the toSignal without computed then it works. However I want to make use of the computed-memoization.

Regular signals also use memoization - they will not notify consumers if the new value is equal to the existing one (source code).