我試圖阻止導航,直到用戶確認他們將丟失他們的更改,但我認為我不能在我的場景中使用路由保護。
這是檢查更改:
public get hasChanged(): boolean {
return this.changeManager.hasChanged({
propA: this.propACtrl.value,
propB: this.propBCtrl.value,
// ETC, lots of other checks
});
}
class ChangeManager {
// bunch of properties containing original values
public hasChanged(args: ChangeManagerArguments): boolean {
return this.propA !== args.propA || this.propB !== args.propB // etc...
}
}
因此,我認為我不能使用服務,因為此檢查是在特定時間完成的,因此服務將沒有該資訊(因為它無法訪問它需要檢查的所有屬性)。
目前,我可以通過以下方式處理用戶使用瀏覽器功能離開頁面(后退按鈕、主頁按鈕、關閉選項卡等)的場景:
@HostListener("window:beforeunload")
public unloadHandler(): boolean {
if (this.hasChanged) {
return false;
}
return true;
}
如果用戶通過 routerLink 導航,我怎么能有類似的東西?有沒有辦法通過路由守衛來實作這一點?
uj5u.com熱心網友回復:
首先需要創建 PendingChangesGuard,如下所示:
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
canDeactivate(component: ComponentCanDeactivate,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot,
nextState: RouterStateSnapshot): boolean | Observable<boolean> {
// if there are no pending changes, just allow deactivation; else confirm first
return component.canDeactivate() ?
true :
confirm('WARNING: You have unsaved changes. Press Cancel to go back and save these changes, or OK to lose these changes.');
}
}
路由路徑添加保護
{ path: 'path...', component: ComponentName, canDeactivate: [PendingChangesGuard] },
//在要檢查更改是否完成的組件中撰寫以下代碼?
@HostListener('window:beforeunload')
canDeactivate(): Observable<boolean> | boolean {
// insert logic to check if there are pending changes here;
// returning true will navigate without confirmation
// returning false will show a confirm dialog before navigating away
if(this.list.length>0){ // Check whatever condition you have
return false;
}
else{
return true;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/529101.html
標籤:有角度的打字稿角度路由
上一篇:找不到型別為“object”錯誤的不同支持物件“[objectObject]”
下一篇:如何以角度獲取資料流
