Skip to content

Instantly share code, notes, and snippets.

@godoway
Created July 12, 2019 00:44
Show Gist options
  • Select an option

  • Save godoway/c8354997a3474c4337b7f635c295596b to your computer and use it in GitHub Desktop.

Select an option

Save godoway/c8354997a3474c4337b7f635c295596b to your computer and use it in GitHub Desktop.
prevent backward
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