Skip to content

Instantly share code, notes, and snippets.

@ezequieltejada
Last active October 12, 2022 11:28
Show Gist options
  • Save ezequieltejada/60cce4e1f33dd5ec8204fd6ba6d1f6e9 to your computer and use it in GitHub Desktop.
Save ezequieltejada/60cce4e1f33dd5ec8204fd6ba6d1f6e9 to your computer and use it in GitHub Desktop.
Simple Store Strategy for Angular
// ... Rest of Component
constructor(
...
private exampleStore: ExampleStore,
...
) {
this.subscriptions$ = [];
}
ngOnInit(): void {
const exampleProperty$ = this.exampleStore.state$.pipe(
pluck('exampleProperty'),
filter(exampleProperty => exampleProperty !== undefined),
distinctUntilChanged(),
// Do whatever is needed with the new state.
);
this.subscriptions$.push(exampleProperty$.subscribe());
}
// ... Rest of Component
import { Injectable } from '@angular/core';
import { Store } from 'src/app/shared/store/store';
const initialState: ExampleState = {
exampleProperty: undefined
};
@Injectable()
export class ExampleStore extends Store<ExampleState>{
constructor() {
super(initialState);
}
methodToChangeState(newValue: string) {
this.setState({
...this.state,
exampleProperty: newValue
});
}
}
https://dev.to/angular/simple-yet-powerful-state-management-in-angular-with-rxjs-4f8g
import { BehaviorSubject, Observable } from 'rxjs';
export class Store<T> {
state$: Observable<T>;
private behaviorState$: BehaviorSubject<T>;
protected constructor(initialState: T) {
this.behaviorState$ = new BehaviorSubject(initialState);
this.state$ = this.behaviorState$.asObservable();
}
get state(): T {
return this.behaviorState$.getValue();
}
setState(nextState: T): void {
this.behaviorState$.next(nextState);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment