Last active
October 12, 2022 11:28
-
-
Save ezequieltejada/60cce4e1f33dd5ec8204fd6ba6d1f6e9 to your computer and use it in GitHub Desktop.
Simple Store Strategy for Angular
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
https://dev.to/angular/simple-yet-powerful-state-management-in-angular-with-rxjs-4f8g |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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