2017-07-19 43 views
2

如果使用页面,我们有要求提醒用户的位置,如果使用选择不同的菜单应用程序,应该用Yes或Yes显示提醒,如果用户继续进行应该发生重定向,否则应该回到同一页面。我们尝试过使用ngOnDestroy,但应用程序正在重定向到下一个页面而没有显示Alert。Angular 2 - 如果触摸页面,则在离开页面之前提醒用户

我的第一种方法是:

ngOnDestroy() 
{   
    this.touched = this.eventForm.touched; 
    if (this.touched) 
     this.display = true; 
} 

现在我用CanDeactivate后卫(指this plunker为例)尝试:

import { Injectable } from '@angular/core'; 
import { CanDeactivate } from '@angular/router'; 
import { SidebarComponent } from './shared/sidebar/sidebar.component'; 

@Injectable() 
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> { 
    canDeactivate(target: SidebarComponent) { 
      if (target.hasChanges()) { 
       return window.confirm('Do you really want to cancel?'); 
      } 
      return true; 
     } 
} 
+0

的可能的复制(https://stackoverflow.com/questions/35922071/warn-user-of- [警告未保存的更改用户离开页面之前] unsaved-changes-before-leaving-page) –

+0

请检查此链接及其下划线的回购 https://rahulrsingh09.github.io/AngularConcepts/#/guard,我已经实施了can decativate警卫。 –

回答

2

您应该使用canDeactivate后卫

https://angular.io/api/router/CanDeactivate

https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html

import { Injectable } from '@angular/core'; 
import { CanDeactivate } from '@angular/router'; 
import { SidebarComponent } from './shared/sidebar/sidebar.component'; 

@Injectable() 
export class ConfirmDeactivateGuard implements CanDeactivate<SidebarComponent> { 
    canDeactivate(target: SidebarComponent) { 
      if (target.hasChanges()) { 
       return window.confirm('Do you really want to cancel?'); 
      } 
      return true; 
     } 
} 

参考样品@plnkr http://plnkr.co/edit/sRNxfXsbcWnPU818aZsu?p=preview

+1

感谢您的帮助Maciej,我已经提到 https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html 试图实现取消激活路由,在此CanDeactivateComponent我是否需要参考我需要禁用的菜单组件?我已经遵循了确切的步骤并注册了ConfirmDeactivateGuard。我是否需要明确调用canDeactivate?这里是我的ConfirmDeactivateGuard。同样已经注册在AppModule中。请协助。 – Pani

+1

import'Injectable} from'@ angular/core'; 从'@ angular/router'导入{CanDeactivate}; 从'./shared/sidebar/sidebar.component'导入{SidebarComponent}; @Injectable() 出口类ConfirmDeactivateGuard实现CanDeactivate { canDeactivate(目标:SidebarComponent){// 如果(target.hasChanges()){ 回报window.confirm('你真的要取消? “); //} //返回true; } } – Pani

+0

据我所见,你的代码应该工作。你有没有遇到任何问题? –

相关问题