Skip to content

Instantly share code, notes, and snippets.

@adamgen
Created May 6, 2020 16:32
Show Gist options
  • Save adamgen/8687435a822aaef825162fbaf5296d1e to your computer and use it in GitHub Desktop.
Save adamgen/8687435a822aaef825162fbaf5296d1e to your computer and use it in GitHub Desktop.
NGRX | Use effects and router-store to isolate route related side ๐Ÿง™๐Ÿผโ€โ™‚๏ธ effects
@Component({
export class MyComponent {
id: string;
id$ = this.activatedRoute.params.pipe(
map(params => params.id),
tap(id => this.id = id),
);
constructor(
private activatedRoute: ActivatedRoute,
) {}
}
setCurrentCourse$ = createEffect(() => this.actions$.pipe(
ofType(ROUTER_NAVIGATED), // get router navigated ngrx actions
mergeMap(() => this.store.pipe(
select(selectRouteParam(โ€˜idโ€™))) // get the id from the router store
),
map((id: string) => setIds({ id })), // dispatch a new action to set the selected id
));
import { Store, select } from โ€˜@ngrx/storeโ€™;
import { Component } from โ€˜@angular/coreโ€™;
@Component({
selector: โ€˜app-rootโ€™,
template: `{{selectedId$ | async | json}}`,
})
export class HomeComponent {
selectedId$ = this.store.pipe(select((state: any) => state.featureName.selectedId));
constructor(
private store: Store,
) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment