angularangular-signalsangular20

toSignal() cannot be called from within a reactive context


When I subscribe and update the signal getting error as follows. any one pls help me to come out of this issue?

Error detail:

ERROR RuntimeError: 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.

  msalInProgressSubscription(): void {
    this.subscription.add(
      this.msalBroadCastService.inProgress$.subscribe((res: string) => {
        if (res === InteractionStatus.None) {
          this.msalInProgressNone$.set(true);//error goes away when i remove
        }
      })
    );
  }

Solution

  • for fix is to separate the creation of the signal from reactive code and avoid calling set() inside something that toSignal owns.

    Move toSignal() outside and just read the signal

    If you’re doing something like:

    msalInProgressNone$ = toSignal(this.msalBroadCastService.inProgress$);

    You shouldn’t be calling .set() on it — instead, use the observable transformation before converting to a signal:

    msalInProgressNone$ = toSignal( this.msalBroadCastService.inProgress$.pipe( map(status => status === InteractionStatus.None) ), { initialValue: false } );