![](/img/trans.png)
[英]Link a guard (canDeactivate) and a component without use RouterModule
[英]Accessing component properties from CanDeactivate guard
我在一個應用程序中有多個表單,我有一個 CanDeactivate 守衛提示用戶確認他們是否要離開頁面而不先保存他們編輯的表單。 每個帶有表單的組件都有一個hasBeenEdited
函數,用於檢查表單是否已被編輯。 由於我只有一個 CanDeactivate 可注入類來處理所有這些帶有表單的組件,因此我需要訪問用戶當前路由到的組件的hasBeenEdited
函數。 如何最好地做到這一點? 我見過這樣的示例,其中向 guard 類中的canDeactivate
函數傳遞了一個組件參數,但我不確定如何傳遞當前路由的組件。
描述 canDeactivate 接口
export interface CanDeactivateComponent {
canDeactivate: () => Observable<boolean> | boolean;
}
描述守衛
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanDeactivateComponent> {
canDeactivate(component: CanDeactivateComponent) {
return component.canDeactivate ? component.canDeactivate() : true;
}
}
描述路線
path: 'yourPath',
canDeactivate: [CanDeactivateGuard],
component: YourComponent
和組件:
...
class YourComponent implements CanDeactivateComponent {
...
canDeactivate() {
... everything you need to detect if you can leave route: return false,
or observable
}
您可以嘗試使用IEdited
界面:
interface IEdited {
hasBeenEdited: (): boolean
}
並讓您的組件實現它,然后也許這會起作用:
@Injectable()
class CanDeactivateEdited implements CanDeactivate<IEdited> {
canDeactivate(
component: IEdited,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): boolean {
return component.hasBeenEdited();
}
}
我正在使用 Angular 5,(我不知道這很重要,)但是接受的答案對我來說還不夠,我了解到我們需要“使用 @NgModule 裝飾器的提供者屬性在應用程序路由模塊中配置守衛”,來源: https://www.concretepage.com/angular-2/angular-candeactivate-guard-example
因此,除了接受的答案之外,我還必須在app-routing.module.ts
中添加如下所示的提供程序:
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers:[CustomExitGuard]
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.