我在一个应用程序中有多个表单,我有一个CanDeactivate保护程序,它提示用户确认他们是否想离开页面,而不首先保存他们编辑过的表单。每个带有窗体的组件都有一个hasBeenEdited函数,用于检查表单是否已被编辑。因为我只有一个CanDeactivate可注入类来使用表单来处理所有这些组件,所以我需要访问用户当前路由到的组件的hasBeenEdited函数。如何才能最好地做到这一点?我看过一些例子,在这些例子中,卫士类中的canDeactivate函数被传递了一个组件参数,但我不知道如何传递当前路由的组件。
发布于 2018-08-31 15:11:01
描述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
}发布于 2018-08-31 15:29:19
您可以尝试使用IEdited接口:
interface IEdited {
hasBeenEdited: (): boolean
}让您的组件实现它,然后它可能会起作用:
@Injectable()
class CanDeactivateEdited implements CanDeactivate<IEdited> {
canDeactivate(
component: IEdited,
currentRoute: ActivatedRouteSnapshot,
currentState: RouterStateSnapshot,
nextState: RouterStateSnapshot
): boolean {
return component.hasBeenEdited();
}
}发布于 2020-11-01 01:03:23
我用的是角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]
})https://stackoverflow.com/questions/52118210
复制相似问题