Simone Nigro
Simone Nigro

Reputation: 4887

Ngrx 16 on Angular 16: NG0600: Writing to signals is not allowed in a computed or an effect by default

I have this HttpInterceptor

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { finalize, catchError } from 'rxjs/operators';
import { Store } from '@ngrx/store';
import { NetworkState } from '../../store/reducers/network.reducer';
import * as networkActions from '../../store/actions/network.actions';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  constructor(private store: Store<NetworkState>) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    this.store.dispatch(networkActions.httpLoadingBegin());
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        return throwError(() => error);
      }),
      finalize(() => {
        this.store.dispatch(networkActions.httpLoadingEnd());
      })
    );
  }

}

Why when the action Is dispached, Angular show this error:

Error: NG0600: Writing to signals is not allowed in a `computed` or an `effect` by default. Use `allowSignalWrites` in the `CreateEffectOptions` to enable this inside effects.
    at core.mjs:26765:15
    at throwInvalidWriteToSignalError (core.mjs:2584:5)
    at WritableSignalImpl.set (core.mjs:2619:13)
    at Object.next (rxjs-interop.mjs:785:30)
    at ConsumerObserver.next (Subscriber.js:91:33)
    at SafeSubscriber._next (Subscriber.js:60:26)
    at SafeSubscriber.next (Subscriber.js:31:18)
    at map.js:7:24
    at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
    at OperatorSubscriber.next (Subscriber.js:31:18)
    at Subject.js:34:30
    at errorContext (errorContext.js:19:9)
    at ReplaySubject.next (Subject.js:27:21)
    at ReplaySubject.next (ReplaySubject.js:22:15)
    at Object.next (ngrx-store-devtools.mjs:831:32)

Upvotes: 1

Views: 3170

Answers (1)

timdeschryver
timdeschryver

Reputation: 15505

See the following issue, https://github.com/ngrx/platform/issues/3932

To fix this, wrap the dispatch in a scheduler

    asapScheduler.schedule(() => this.store.dispatch(actions.someAction()));

Upvotes: 4

Related Questions