2017-07-19 181 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

據我所見,你的代碼應該工作。你有沒有遇到任何問題? –

相關問題