Skip to content

Instantly share code, notes, and snippets.

@glendaviesnz
Last active December 14, 2018 02:58
Show Gist options
  • Save glendaviesnz/0390e1213837d61028d02bf021cc8628 to your computer and use it in GitHub Desktop.
Save glendaviesnz/0390e1213837d61028d02bf021cc8628 to your computer and use it in GitHub Desktop.
NgRX State Machine - component state service
// the component uses an injected componentStateService to register its state transitions
this._componentStateService.addComponentStates(componentStates);
// the component state service is reasonably simple and just maintains a lookup object of all the registered
// state transitions, and also has methods for cleaning these up when components are destroyed
@Injectable()
export class ComponentStateService {
public componentStates: any = {};
constructor(private _store: Store<RootState>) {
Guard.notNothing(_store, '_store');
}
public addComponentStates(componentStateData: any) {
this.deleteComponentState(componentStateData.name);
forOwn(componentStateData.states, (value: any, key: string) => {
if (!this.componentStates[key]) {
this.componentStates[key] = {};
}
if (!this.componentStates[key][componentStateData.name]) {
if (componentStateData.id) {
value.id = componentStateData.id;
}
this.componentStates[key][componentStateData.name] = value;
}
});
}
public removeComponentStates(componentName: string) {
forOwn(this.componentStates, (value: any, key: string) => {
if (value[componentName]) {
delete this.componentStates[key][componentName];
}
if (isEmpty(this.componentStates[key])) {
delete this.componentStates[key];
}
});
this.deleteComponentState(componentName);
}
public updateComponentState(componentName: string, uiState: ComponentStates) {
this._store.dispatch(new UpdateComponentStateAction({ componentName, uiState }));
}
public deleteComponentState(componentName: string) {
this._store.dispatch(new DeleteComponentStateAction({ componentName }));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment