Last active
April 4, 2018 14:03
-
-
Save ghetolay/9e58eace9098994967cd6d967ff99424 to your computer and use it in GitHub Desktop.
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
@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