简体   繁体   中英

State Management in Angular without using Libraries

I'm using a data table (using Material Data Tables) in my application and I want to build a simple example where I'm saving the state of the thee filters without using libraries such as NGRX etc.

My issue is small enough not to use an entire library at this point; what are ways that I am able to do this?

Super simple state utility can be like something below.

this.state = {}
this.setState = (key,value) => this.state={...this.state,key:value}

you can put that in a singleton share service.

You can have simple state service using rxjs

import { BehaviorSubject } from 'rxjs';
import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class StateService {
    private _state$ = new BehaviorSubject({});

    dispatchUserLoggedStatus(status) {
        this._state$.next({
            ...this._state$.value,
            isLogged: status
        });
    }

    get state$() {
        return this._state$.asObservable();
    }
}

The point of using librraries is when you need extra features

this is a good solution by using rxjs-observable-store , the The store's state is a BehaviorSubject, you can subscribe to the state updates in your components

this.store.state$.subscribe(state => {
  // Logic to execute on state update
});

or using

this.store.state;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM