[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) - ;
}
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 { }
[Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- [Angular2 Router] Guard: CanLoad
'canLoad' guard can decide whether a lazy load module can be loaded or not. @Injectable() export cla ...
- [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 ...
- [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 ...
- Angular2 Router路由相关
路由设置 Angular中路由的配置应该按照先具体路由到通用路由的设置,因为Angular使用先匹配者优先的原则. 示例: 路由设置如下: export const reportRoute: Rout ...
随机推荐
- python的使用环境总结
python在linux上运行,使用的是vim,每次都是敲四个空格进行缩进,真尼玛的蛋疼,书本果然是个好东西,从而根据书本python高级编程中的设置配置而来: 1.进行自动补全的脚本 [root@p ...
- mybatis源码学习: 动态代理的应用(慢慢改)
动态代理概述 在学spring的时候知道使用动态代理实现aop,入门的列子:需要计算所有方法的调用时间.可以每个方法开始和结束都获取当前时间咋办呢.类似这样: long current=system. ...
- c++11之智能指针
在c++98中,智能指针通过一个模板“auto_ptr”来实现,auto_ptr以对象的方式来管理堆分配的内存,在适当的时间(比如析构),释放所获得的内存.这种内存管理的方式只需要程序员将new操作返 ...
- chrome 浏览器 开发者工具 性能检测 参数解释
Sending is time spent uploading the data/request to the server. It occurs between blocking and waiti ...
- Cocos2d-JS v3.0 alpha 导入 cocostudio的ui配置
1.在新项目的根文件夹下打开project.json文件,修改: "modules" : ["cocos2d", "extensions", ...
- VS2010 删除空行
查找内容:^:b*$\n 替换为: 查找范围:当前文档 使用:正则表达式 vs2013 ^\s*(?=\r?$)\n
- 第三百二十七天 how can I 坚持
都没心情学习了,睡觉.太失败了. 好了,你赢了,最怕女人不说话了,我妈一生气就不说话,有点怕我妈,你想删就把我删了吧,我不怪你. 给你个善意的建议,任何事情都要有度,过犹而不及,你是属于那种比较听家 ...
- 查看MySql中每个IP的连接数
要统计数据库的连接数,我们通常情况下是统计总数,没有细分到每个IP上.现在要监控每个IP的连接数,实现方式如下: ) as ip , count(*) from information_schema. ...
- Jtemplates 基本语法
jTemplates是一个基于JQuery的模板引擎插件,功能强大,有了他你就再不用为使用JS绑定数据集时发愁了. 首先送上jTtemplates的官网地址:http://jtemplates.tpy ...
- GLSL Notes
[GLSL Notes] API of shader: glCreateShader(), glShaderSource(), glCompileShader(), glGetShadrInfoLog ...