2016-02-29 78 views
1

routerCanDeactivate()已成功阻止從組件導航。Angular2:如何在執行routerCanDeactivate時防止/取消歷史操作?

routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) 
    { 
    return confirm("Do you want to discard unsaved changes ?"); 
    } 

但是,如果導航是由瀏覽器的back按鈕或任何其他history.back()觸發,

造成的,它不保留歷史記錄完整,在每次觸發觸發popState並最終定位到瀏覽器的主頁(測試鉻)。


編輯:

我在一個變量currentLocation

保存當前組件的網址試圖操縱historyhistory api

只是無法搞清楚正確的順序api電話需要保持完好。

routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) { 
    history.replaceState(null,null, this.currentLocation); 
    history.forward(); 
    return confirm("Do you want to discard unsaved changes ?"); 
    } 

回答

1

由於window.onpopstate在每一個後退按鈕點擊觸發,

我認爲一個pushState是必需的。但事實並非如此,下面的代碼完美無缺。

routerCanDeactivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) { 
    if(confirm("Do you want to discard unsaved changes ?")){ 
     return true; 
    } 
    else { 
     history.forward(); 
     return false; 
    } 
    } 

但是,這將是很好,如果有人能解釋發生了什麼,因爲我沒有的history api很多知識。