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) - ;
} next(){
return Number(this.heroId) + ;
}
}

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 { }

Github

[Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route的更多相关文章

  1. [Angular2 Router] CanActivate Route Guard - An Example of An Asynchronous Route Guard

    In this tutorial we are going to learn how we can to configure an can activate route guard in the An ...

  2. [Angular2 Router] Resolving route data in Angular 2

    From Article: RESOLVING ROUTE DATA IN ANGULAR 2 Github If you know Anuglar UI router, you must know ...

  3. [Angular2 Router] Exiting an Angular 2 Route - How To Prevent Memory Leaks

    In this tutorial we are going to learn how we can accidentally creating memory leaks in our applicat ...

  4. [Angular2 Router] Optional Route Query Parameters - The queryParams Directive and the Query Parameters Observable

    In this tutorial we are going to learn how to use the Angular 2 router to pass optional query parame ...

  5. [Angular2 Router] Configuring a Home Route and Fallback Route - Learn An Essential Routing Concept

    In this tutorial we are going to learn how to configure the Angular 2 router to cover some commonly ...

  6. [Angular2 Router] Guard: CanLoad

    'canLoad' guard can decide whether a lazy load module can be loaded or not. @Injectable() export cla ...

  7. [Angular2 Router] Load Data Based on Angular 2 Route Params

    You can load resource based on the url using the a combination of ActivatedRouteand Angular 2’s Http ...

  8. [Angular2 Router] Configure Auxiliary Routes in the Angular 2 Router - What is the Difference Towards a Primary Route?

    In this tutorial we are going to learn how we can can configure redirects in the angular 2 router co ...

  9. Angular2 Router路由相关

    路由设置 Angular中路由的配置应该按照先具体路由到通用路由的设置,因为Angular使用先匹配者优先的原则. 示例: 路由设置如下: export const reportRoute: Rout ...

随机推荐

  1. 【LeetCode】223 - Rectangle Area

    Find the total area covered by two rectilinear rectangles in a 2D plane. Each rectangle is defined b ...

  2. leetcode:Palindrome Number

    Question: Determine whether an integer is a palindrome. Do this without extra space. Some hints: Cou ...

  3. Quartz与Spring集成

    关于Quartz的基本知识,这里就不再多说,可以参考Quartz的example. 这里主要要说的是,个人在Quartz和Spring集成的过程中,遇到的问题和个人理解. 首先来说说个人的理解: 1. ...

  4. 【C#】构造函数的特点

    1.它的函数名与类名相同:2.它可以重载:3.不能指定返回类型,即使是void也不行:4.虽然在一般情况下,构造函数不被显式调用,而是在创建对象时自动被调用.但是并不是不能被显示调用.有些时候是一定要 ...

  5. 渗透测试实例Windows XP SP2

    一.msf> use exploit/windows/dcerpc/ms03_026_dcom.看到命令提示符的改变表明该命令已经运行成功. 二.为漏洞利用代码设置必要的参数,show opti ...

  6. ASP.NET MVC 常用内置验证特性 简介

    1.[Required] : 必须输入 [Required(ErrorMessage = "请输入用户名")] 2.[StringLength] : 限制字符串长度 [String ...

  7. TopFreeTheme精选免费模板【20130827】

    今天我们整理了一些关于WordPress, Joomla, Drupal, Magento, OpenCart的最新免费模板主题,绝大多数都是来自ThemeForest的响应式风格模板主题.题材多样化 ...

  8. Error when running Swift3 in REPL

    Traceback (most recent call last): File "", line 1, in NameError: name 'run_one_line' is n ...

  9. jquerymobile,手机端click无效

    1.直接把<script>放到html代码后面,不要放到@section里面. 2.使用代理.如下所示: <script type="text/javascript&quo ...

  10. var隐式类型

    var dogName = "ruiky"; 1.[编译器]会在编译时自动根据值的类型推断这个变量的类型:       2.变量类型不可更改:因为声明的时候已经确定类型了. 3.可 ...