Angular toSignal's read-only result as a writable signal

Discussão em 'Angular' iniciado por Dima Savenkov, Dezembro 12, 2024.

  1. In my Angular service, I currently have a signal variable loginById$$ initialized from an observable:

    public loginById$$: Signal = toSignal(this.getLoginById(), { initialValue: {} as LoginResponse });


    Here is the getLoginById method implementation.

    private getLoginById(): Observable<LoginResponse> {
    return toObservable(this._id$$).pipe(
    tap(() => this._isLoading.set(true)),
    switchMap((id) =>
    (id ? this.dataService.getLoginById(id) : of(null)).pipe(finalize(() => this._isLoading.set(false))),
    ),
    );
    }


    Every change in the _id$$ signal triggers a new request. However, loginById$$ created via toSignal() is read-only, and I need to programmatically update this data at certain points.

    I've considered the following solutions:

    • Use a separate Subject and merge its stream with getLoginById before converting to a signal.
    • Create a writable signal with computed that wraps toSignal(...). computed(() => signal(...))
    • Subscribe to getLoginById() manually in constructor and feed data into a writable signal via .set()

    Can someone help me to find a workaround that are best suited in this situation?

    Continue reading...

Compartilhe esta Página