Skip to content

Instantly share code, notes, and snippets.

@ghetolay
Last active April 4, 2018 14:03
Show Gist options
  • Save ghetolay/9e58eace9098994967cd6d967ff99424 to your computer and use it in GitHub Desktop.
Save ghetolay/9e58eace9098994967cd6d967ff99424 to your computer and use it in GitHub Desktop.
@Injectable()
export class NgrxStoreService {
ondestroy$: Observable<void> = new Subject<void>();
constructor(protected store: Store<State>, protected changeDetector: ChangeDetectorRef) { }
select<R>(mapFunc: (state: State) => R): Observable<R> {
return this.store.select(mapFunc).pipe(
takeUntil(this.ondestroy$),
tap(() => { this.changeDetector.markForCheck(); })
);
}
set<R>(mapFunc: (state: State) => R, next?: (v: R) => void, error?: (e: any) => void, complete?: () => void) {
this.select(mapFunc)
.subscribe(next, error, complete);
}
dispatch(action: Action) {
this.store.dispatch(action);
}
ngOnDestroy() {
(<any>this.ondestroy$).next();
(<Subject<void>>this.ondestroy$).complete();
}
}
//usage
@Component({
// /!\ important part don't forget it (kind of annoying too)
providers: [NgrxStoreService]
})
export class Component {
constructor(private store: NgrxStoreService) {
store.set( getSelectedItem, item => this.item = item );
store.select( getSelectedItem ).subscribe(...);
store.dispatch( SelectAction() );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment