Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jsonberry
Last active November 9, 2018 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsonberry/bfd69c948812d2dfd690ae1381d83bf4 to your computer and use it in GitHub Desktop.
Save jsonberry/bfd69c948812d2dfd690ae1381d83bf4 to your computer and use it in GitHub Desktop.
Angular ngrx-router-store Router Actions / Effects
/* tslint:disable:max-classes-per-file */
import {Action} from '@ngrx/store';
import {NavigationExtras} from '@angular/router';
export enum RouterActionTypes {
GO = '[router] Go',
BACK = '[router] Back',
FORWARD = '[router] Forward',
}
export class Go implements Action {
readonly type = RouterActionTypes.GO;
constructor(
public path: any[],
public query?: object,
public extras?: NavigationExtras,
) {}
}
export class Back implements Action {
readonly type = RouterActionTypes.BACK;
}
export class Forward implements Action {
readonly type = RouterActionTypes.FORWARD;
}
export type RouterAction =
| Go
| Back
| Forward;
import {Location} from '@angular/common';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import 'rxjs/observable/empty';
import {ROUTER_NAVIGATION} from '@ngrx/router-store';
import {Actions, Effect, ofType} from '@ngrx/effects';
import {map, tap} from 'rxjs/operators';
import * as fromRouter from '../actions/router.actions';
@Injectable()
export class RouterEffects {
constructor(
private actions$: Actions,
private router: Router,
private location: Location,
) {}
@Effect({dispatch: false})
goEffect$ = this.actions$.pipe(
ofType<fromRouter.Go>(fromRouter.RouterActionTypes.GO),
tap(({path, query: queryParams, extras}) =>
this.router.navigate(path, {queryParams, ...extras}),
),
);
@Effect({dispatch: false})
backEffect$ = this.actions$.pipe(
ofType<fromRouter.Back>(fromRouter.RouterActionTypes.BACK),
tap(() => this.location.back()),
);
@Effect({dispatch: false})
forwardEffect$ = this.actions$.pipe(
ofType<fromRouter.Forward>(fromRouter.RouterActionTypes.FORWARD),
tap(() => this.location.forward()),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment