Last active
November 9, 2018 21:23
-
-
Save jsonberry/bfd69c948812d2dfd690ae1381d83bf4 to your computer and use it in GitHub Desktop.
Angular ngrx-router-store Router Actions / Effects
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
/* 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; |
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
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