Encapsulate behaviorSubject in a service

Discussão em 'Angular' iniciado por Krzysztof Przybylski, Abril 16, 2025.

  1. I would like to hide the "next" interface of a BehaviorSubject while retaining its other properties, especially the possibility to get last emitted value imperatively. The idea is all state manipulation can be done on a private BehaviorSubject within a service and all I expose is what I would call a "ReadonlySubject" that does not have "next" method. The only idea I have so far is something like this:

    export class ReadonlyBehaviorSubject<T> extends BehaviorSubject<T> {
    override next(_value: T) {
    console.error('cannot set value on a readonly BehaviorSubject');
    }
    }

    export function toReadonlyBehaviorSubject<T>(bs: BehaviorSubject<T>): ReadonlyBehaviorSubject<T> {
    return new ReadonlyBehaviorSubject(bs.value);
    }


    As you can see we still have "next" method - it just does nothing, but informs the user that they cannot set a value on ReadonlyBehaviorSubject. Is there something neater? Preferably not exposing "next" method at all?

    Continue reading...

Compartilhe esta Página