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. linux笔记_20150417_ubuntu 常见问题_文件_音乐播放器

    最近在学习ubuntu的过程中,遇到了一些问题,就记下来了它的解决办法.以希望对你也有用. ),至少保证周围局域网内用户可以访问.至于配置文件,内容比较少,反正对我来讲能用就ok了~不知道会不会很弱 ...

  2. nginx指令

    Directives(指令) Syntax(语法): aio on | off | threads[=pool]; Default: aio off; Context: http, server, l ...

  3. oracle数据库建表

    create or replace directory dumpdir as 'E:\oracle\dumpdir';create temporary tablespace ydxt_temp tem ...

  4. tomcat 粗略笔记

    GlobalNamingResources 存在于server.xml中,定义全局公共数据源,如果host中有大量引用相同的数据源,那么可以都配在这里 <GlobalNamingResource ...

  5. 技术文集:万能WINDOWS XP封装

    这里将系统封装分为3步:做系统.封装.部署 一.做系统 平台不限,但不建议在虚拟机上制作.CPU及主板芯片没有限制,关于intelide和intelppm的不兼容问题,深度白金3in1并没有删除这些注 ...

  6. 深入理解inode与软硬链接

    一.inode是什么? 理解inode,要从文件储存说起. 文件储存在硬盘上,硬盘的最小存储单位叫做"扇区"(Sector).每个扇区储存512字节(相当于0.5KB). 操作系统 ...

  7. Telnet连接Win7系统被拒绝的原因及解决方法

    有时要与计算机进行远程连接,会用到telnet.win7中telnet默认是没有开启的,所以这时连接会连接失败,其失败提示如下: 正在连接192.168.100.103...无法打开到主机的连接. 在 ...

  8. HDU 5794 A Simple Chess (Lucas + dp)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5794 多校这题转化一下模型跟cf560E基本一样,可以先做cf上的这个题. 题目让你求一个棋子开始在( ...

  9. Lotus 迁移到Exchange 2010 之准备使用Transport 同步Lotus 相关信息!

    这里我们先来分析下Lotus迁移到Exchange2010 的一些原理,由于存在一定周期的共存时间,因此在共存期间必须来实现相应的同步计划,整个同步计划包含了如下的同步计划:

  10. UI进阶 FMDB

    一.FMDB简介 1.FMDB简介 iOS中原生的SQLite API在进行数据存储的时候,需要使用C语言中的函数,操作比较繁琐.于是,就出现了一系列将SQLite API进行封装的库,例如FMDB. ...