[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 ...
随机推荐
- C++中cin、cin.get()、cin.getline()、getline()、gets()等函数的用法----细节决定成败 (sort用法)
C++中cin.cin.get().cin.getline().getline().gets()等函数的用法 学C++的时候,这几个输入函数弄的有点迷糊:这里做个小结,为了自己复习,也希望对后来者能有 ...
- public static void main(String arg[])
该语句定义了main方法. main方法是程序执行的入口,所有的java程序都必须具备一个main()方法,而且必须按照如上的格式来定义. 不具有main方法的类可以编译,但不能执行.因为它没有m ...
- [转]Javascript定义类的三种方法
作者: 阮一峰 原文地址:http://www.ruanyifeng.com/blog/2012/07/three_ways_to_define_a_javascript_class.html 将近2 ...
- JavaEE5 Tutorial_Jsp,EL
Jsp的各种元素在转化为servlet时处理是不一样的:指令,控制web容器如何处理页面脚本,被插入到生成的servlet里EL表达式,作为参数传递到解析器get/set Property,变成方 ...
- Eralng 小知识点
文件属性 提取方法:Module:module_info/1 头文件 包含头文件 -include(FileName). %% FileName为绝对路径或相对路径 引入库中包含文件 -include ...
- Java基础 —— CSS
CSS:层叠样式表(Cascading Style Sheets) --> 提高显示功能,定义样式 html提供了div与span,只为了封装文本数据,div为一行数据,span为行内的数据. ...
- dom 回到顶部(兼容IE FF Chrome)
<!doctype html> <html> <head> <meta charset="utf-8"> <title> ...
- 如何判断ios设备是否是高清屏幕
if([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2f) { CGRect winRect = [[UIScreen m ...
- Uber新功能:隐藏司机乘客们的手机号码
滴快车单单2.5倍,注册地址:http://www.udache.com/ 如何注册Uber司机(全国版最新最详细注册流程)/月入2万/不用抢单:http://www.cnblogs.com/mfry ...
- NetBeans IDE 7.4 Beta版本build JavaFX时生成的可执行jar包执行时找不到依赖的jar包
现象,执行时抛出java.lang.ClassNotFoundException异常: Executing E:\secondegg\secondegg-reversi\dist\run8022211 ...