[Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route
In this tutorial we are going to learn how we can to configure an exit guard in the Angular 2 Router. We are going to learn how to use a CanDeactivate route guard to ask the user if he really wants to exist the screen, giving the user to for example save data that was not yet persisted.
What 'canDeactivate' do is for example, you are editing a form, and you click other page by mistake, system will show a confirm dialog to ask whether you want to stay this page.
So first, add input box in hero component, when you type something and press enter, will edit the 'editing' variable to 'true', then we use this variable to control.
import { Component, OnInit, OnDestroy, ViewChild, } from '@angular/core'; import {ActivatedRoute, Router} from "@angular/router"; import {StarWarsService} from "../heros.service"; import {Observable, Subscription} from "rxjs"; @Component({ selector: 'app-hero', templateUrl: 'hero.component.html', styleUrls: ['hero.component.css'] }) export class HeroComponent implements OnInit, OnDestroy { @ViewChild('inpRef') input; heroId: number; hero: Observable<any>; description: string; querySub: Subscription; editing: boolean = false; constructor(private route: ActivatedRoute, private router: Router, private starwarService: StarWarsService) { } ngOnInit() { this.hero = this.route.params .map((p:any) => { this.editing = false; this.heroId = p.id; return p.id; }) .switchMap( id => this.starwarService.getPersonDetail(id)); /* // since herocomponent get init everytime, it would be better to use snapshot for proferemence this.heroId = this.route.snapshot.params['id']; this.hero = this.starwarService.getPersonDetail(this.heroId);*/ this.querySub = this.route.queryParams.subscribe( param => this.description = param['description'] ); console.log("observers", this.route.queryParams['observers'].length) } ngOnDestroy() { this.querySub.unsubscribe() } saveHero(newName){ this.editing = true; console.log("editing", this.editing) } prev(){ return Number(this.heroId) - 1; } next(){ return Number(this.heroId) + 1; } }
Because now, from our hero compoennt, we can navigate to other hero component, so snapshot is not ideal for this case, we need to use router.params.
<div> <h2>{{description}}: {{(hero | async)?.name}}</h2> <div> <a [routerLink]="['/heros', prev()]">Previous</a> <a [routerLink]="['/heros', next()]">Next</a> </div> <div> <input type="text" #inpRef (keyup.enter)="saveHero(inpRef.value)"> </div> <br> <img src="{{(hero | async)?.image}}" alt=""> <div> <a [routerLink]="['/heros']">Back</a> </div> </div>
CanDeactivateHero.ts:
import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router"; import {Observable} from "rxjs"; import {HeroComponent} from "./hero/hero.component"; export class CanHeroDeactivate implements CanDeactivate<HeroComponent>{ canDeactivate(component: HeroComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|boolean { if(!component.editing){ return true; } return confirm('You have unsaved message, are you sure to leave the page?') } }
Heros.router.ts:
import {HerosComponent} from "./heros.component"; import {RouterModule} from "@angular/router"; import {HeroComponent} from "./hero/hero.component"; import {CanHeroDeactivate} from "./CanDeactiveHero.directive"; const routes = [ {path: '', component: HerosComponent}, {path: ':id', component: HeroComponent, canDeactivate: [CanHeroDeactivate]}, ]; export default RouterModule.forChild(routes)
heros.module.ts:
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { HerosComponent } from './heros.component'; import herosRoutes from './heros.routes'; import {HeroComponent} from "./hero/hero.component"; import {StarWarsService} from "./heros.service"; import {RouterModule} from "@angular/router"; import {CanHeroDeactivate} from "./CanDeactiveHero.directive"; @NgModule({ imports: [ CommonModule, herosRoutes ], declarations: [HerosComponent, HeroComponent], providers: [StarWarsService, CanHeroDeactivate] }) export default class HerosModule { }
相关文章
- str_to_map使用
- 记录一次在生成数据库服务器上出现The timeout period elapsed prior to completion of the operation or the server is not responding.和Exception has been thrown by the target of an invocation的解决办法
- Introduction to Windows 8: The Definitive Guide for Developer
- [React] Use the useReducer Hook and Dispatch Actions to Update State (useReducer, useMemo, useEffect)
- [Redux-Observable && Unit Testing] Use tests to verify updates to the Redux store (rxjs scheduler)
- [TypeScript] Configuring TypeScript Which Files to Compile with "Files" and "OutDir"
- [Redux] Persisting the State to the Local Storage
- Caused by: org.xml.sax.SAXParseException: The reference to entity "characterEncoding" must end with the ';' delimiter.
- Windows下pip安装包报错:Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat
- [HTML5] Add Semantic Styling to the Current Page of a Navigation Item with aria-current
- [D3] Add image to the node
- [Protractor] Use protractor to catch errors in the console
- 解决 Jenkins 中无法展示 HTML 样式的问题,csp问题,Refused to apply inline style because it violates the following Content Security Policy directive: "style-src 'self'".
- error: pathspec 'master' did not match any file(s) known to git.
- Unable to read the project file 'client.csproj'. Could not load file or assembly 'Microsoft.Build.En
- AndroidStudio3.0 注解报错Annotation processors must be explicitly declared now. The following dependencies on the compile classpath are found to contain annotation processor.
- how to find the corresponding ERP system of given CRM system
- git push报错 fatal: The current branch master has no upstream branch. To push the current
- You currently don‘t have access to this membership resource. To resolve this issue, agree to the lat
- 成功解决To fix this you could try to: 1. loosen the range of package versions you‘ve specified
- 成功解决h5py_init_.py:26:FutureWarning: Conversion of the second argument of issubdtype from `float` to
- 已解决pyautogui.FailSafeException: PyAutoGUI fail-safe triggered from mouse moving to a corner of the s
- Introduction to nonlinear optimization第二章习题
- 【问题解决】The connection to the server localhost:8080 was refused
- macOS The bottle needs the Xcode CLT to be installed
- Error:The supplied javaHome seems to be invalid. I cannot find the java executable. Tried location:
- Kubernetes-kubectl The connection to the server localhost:8080 was refused -did you specify