Home > OS >  How to manage state in Angular using services and BehaviorSubject?
How to manage state in Angular using services and BehaviorSubject?

Time:11-16

I don't know NgRx yet and I need to manage state in an Angular app, the app is pretty simple, we have list of items, when user goes to items list I download that data and show it, but when user navigates to admin page and then comes back to items list component I don't want to download items list again. Can I manage state in Angular using services and BehaviorSubject? And what is the easiest way to manage state in simple Angular application (if it's possible without using NgRx)?

CodePudding user response:

Do you want to use an BehaviorSubject to store the data or do you want to use a global state like NgRx store? These are two different things. Nevertheless from your question I assume that you want to use a service for this.

You can just create a simple service for this:

@Injectable()
export class ItemService {
  items$ = this.loadItems().pipe(shareReplay());
}

This will result in loadItems() (the function where the HTTP observable will be returned) gets called only for the first subscription to this observable. After that new subscribers will receive the latest value from it.

After that you can inject this service in other components and use the async pipe to subscribe to the items$ observable.

CodePudding user response:

You can use it like this for immutable state:

    private readonly _someStateObj: BehaviorSubject<any> = new BehaviorSubject<any>('initial default value');
    public someStateObj: Observable<any> = this._someStateObj.asObservable();

To get the current value use:

get currentValueOfStateObj(): any {
    return this._someStateObj.value;
}

Use this to emit new values in the store (service) file:

this._someStateObj.next(area);

In the components you can inject the services and subscribe to someStateObj or get it's current value with the getter. If you do not need to hold state but only need to emit values use Subject instead.

  • Related