博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Angular2 Router] CanDeactivate Route Guard - How To Confirm If The User Wants To Exit A Route
阅读量:5176 次
发布时间:2019-06-13

本文共 4145 字,大约阅读时间需要 13 分钟。

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
; 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.

 

{
{description}}: {
{(hero | async)?.name}}

 

CanDeactivateHero.ts:

import {CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";import {Observable} from "rxjs";import {HeroComponent} from "./hero/hero.component";export class CanHeroDeactivate implements CanDeactivate
{ canDeactivate(component: HeroComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable
|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 { }

 

转载于:https://www.cnblogs.com/Answer1215/p/5924169.html

你可能感兴趣的文章
点击屏幕其他地方让软键盘消失
查看>>
js去后台传递的值
查看>>
Python之numpy基本指令
查看>>
Quartz.Net - Lesson2: 任务和触发器
查看>>
centos7下安装Node.js MongoDB Nginx
查看>>
rest_framework 权限流程
查看>>
flask_sqlalchemy
查看>>
ImageView
查看>>
asp.net RDLC报表入门
查看>>
Java——Iterate through a HashMap
查看>>
Android Studio 工程的 .gitignore
查看>>
伪Textatea的构建(div+table),以及相应的滚动条问题与safari上的优化
查看>>
简单的一个月之设计实现内容2
查看>>
DataTables源码分析(一)
查看>>
javascript
查看>>
阿里巴巴Java规约插件试用
查看>>
Thunk 技术的一个改进
查看>>
ACE反应器(Reactor)模式(4)
查看>>
青蛙学Linux—Apache配置文件
查看>>
斯特林大数公式求阶乘位数
查看>>