Reasons for not using a data state container for your angular application
first of all, we need some context. i don't want to vilify state data
containers, i just want to raise the question, do we really need them in
angular apps?
I would argue that angular is well prepped for almost all the use cases that
might make you decide that a state management tool would be required.
first state management was crafted by the react founders. and it served one
purpose, and it did it quite well for a while. that purpose is to easily share
data among a highly hierarchical tree of components.
do we have something in angular that serves this purpose? of course, we have
services. which are injected by the framework to any component that registers
to that service. having said that, a service can have a private subject that
will hold the data, and will be used for updating it, depending on user
actions. the same service would have then a public observable created from the
subject holding the data. we would need one more thing, to make the observable
post data for late subscribers. In some cases, when the application is loaded, we can provide a set of initial data. This can be done with a behaviour subject. NOTE: behavior subjects replay the data by default, no need to pipe the data and attach the shareReplay operator.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
import { shareReplay } from 'rxjs/operators';
type product = {
name: string
}
@Injectable({
providedIn: 'root'
})
export class ProductService {
private readonly products: BehaviorSubject<product> = new BehaviorSubject<product>(null);
public readonly products$ = this.products.asObservable();
private readonly pr: Subject<number> = new Subject();
public readonly pr$ = this.pr.pipe(
shareReplay(1)
);
}
this is just the most basic service that behaves like a small redux like data state manager.
interesting point.
ReplyDelete