Created
July 12, 2019 00:44
-
-
Save godoway/c8354997a3474c4337b7f635c295596b to your computer and use it in GitHub Desktop.
prevent backward
This file contains hidden or 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 { Injectable } from '@angular/core'; | |
| import { ActivatedRouteSnapshot, CanDeactivate, RouterStateSnapshot, UrlTree } from '@angular/router'; | |
| import { Observable } from 'rxjs'; | |
| import { tap } from 'rxjs/operators'; | |
| export interface CanComponentDeactivate { | |
| canDeactivate: () => Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree; | |
| } | |
| @Injectable({ | |
| providedIn: 'root' | |
| }) | |
| export class BackwardGuard implements CanDeactivate<CanComponentDeactivate> { | |
| canDeactivate(component: CanComponentDeactivate, | |
| currentRoute: ActivatedRouteSnapshot, | |
| currentState: RouterStateSnapshot, | |
| nextState?: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree { | |
| let rs = component.canDeactivate ? component.canDeactivate() : true; | |
| if (rs instanceof Promise) { | |
| rs = rs.then(next => { | |
| if (next === false) { | |
| history.pushState(null, null, location.href); | |
| } | |
| return next; | |
| }); | |
| } | |
| if (rs instanceof Observable) { | |
| rs = rs.pipe( | |
| tap(next => { | |
| if (next === false) { | |
| history.pushState(null, null, location.href); | |
| } | |
| }) | |
| ); | |
| } | |
| if (rs === false) { | |
| history.pushState(null, null, location.href); | |
| } | |
| return rs; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment