Create a Store
Our first task is to create a store in our simple-store project. All commands assume your current directory is the course directory.
To get started, create a new store directory and create the following files:
- actions.ts
- model.ts
- reducers.ts
- store.ts
mkdir projects/simple-store/src/app/store
touch projects/simple-store/src/app/store/actions.ts
touch projects/simple-store/src/app/store/models.ts
touch projects/simple-store/src/app/store/reducers.ts
touch projects/simple-store/src/app/store/store.ts
Open the store.ts file.
Interfaces
First, create the Action
interface.
Each action will be a class that implements this interface, which simply requires the type
string property.
export interface Action {
type: string;
}
Next, create a ReducerMap
interface.
This interface will be used to define the reducer functions associated with each property in the state object.
export interface ReducerMap {
[key: string]: Function;
}
Finally, create the State
interface.
This interface represents the state object.
export interface State {
[key: string]: any;
}
Store
Class
Create a new Store
class:
export class Store {
private state$ = new BehaviorSubject<State>(null);
constructor(public reducers: ReducerMap, private state: State = {}) {}
dispatch(action: Action) {
this.notify(action);
this.state$.next(this.state);
}
notify(action: Action) {
Object.keys(this.reducers).forEach(key => {
this.state[key] = this.reducers[key](this.state[key], action);
});
}
subscribe(
next: (value: State) => void,
error?: (error: any) => void,
complete?: () => void
) {
return this.state$.subscribe(next, error, complete);
}
}
- The
state$
property is a newSubject
that subscribers can subscribe to. - The
constructor()
function requires areducers
object along with an optionalstate
object, which defaults to an emptyObject
. - The
dispatch()
method accepts anaction
and then invokes thenotify
method and emits a next notification to thestate$
subject using thenext()
method. - The
notify()
method accepts anaction
and then invokes thereducer()
function for each slice of state, updating thestate
object. - The
subscribe()
method requires anext
argument, which is a function that accepts theState
and returns void. Theerror
andcomplete
arguments are optional. The method returns a newSubscription
to thestate$
subject.