【问题标题】:Angular 2 - Alert user before leaving the page if page is touchedAngular 2 - 如果页面被触摸,则在离开页面之前提醒用户
【发布时间】:2017-07-19 14:54:12
【问题描述】:

我们有要求,如果页面被触摸,我们必须提醒用户,如果使用选择不同的菜单应用程序,如果用户继续继续,则应该显示是或否的警报,那么只有重定向应该发生,否则它应该回退到同一页面。我们已经尝试使用 ngOnDestroy,但是应用程序正在重定向到下一页而不显示警报。

我的第一个方法是:

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

【问题讨论】:

标签: angular


【解决方案1】:

你应该使用canDeactivateguard

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

【讨论】:

  • 感谢您的帮助 Maciej,我已经提到 blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html 试图实现停用路由,在这个 CanDeactivateComponent 中我需要参考我需要禁用的菜单组件吗?我已经按照确切的步骤注册了 ConfirmDeactivateGuard。我需要明确调用 canDeactivate 吗?这是我的 ConfirmDeactivateGuard。同样已在 AppModule 中注册。请帮忙。
  • 从'@angular/core'导入{可注入};从“@angular/router”导入 { CanDeactivate };从'./shared/sidebar/sidebar.component'导入{ SidebarComponent }; @Injectable() export class ConfirmDeactivateGuard implements CanDeactivate { canDeactivate(target: SidebarComponent) { //if (target.hasChanges()) { return window.confirm('Do you really want to cancel?'); //} // 返回真; } }
  • 据我所知,您的代码应该可以正常工作。你有什么问题吗?
猜你喜欢
  • 2015-07-21
  • 2020-10-22
  • 1970-01-01
  • 1970-01-01
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多