为子组件启用 candeactivate

Enable candeactivate for child component

我正在开发一个 angular 应用程序,如果用户在编辑时离开了未保存更改的页面,我需要显示一条警告消息。

我已经为此在路由中创建并注册了一个 candeactivate 守卫,它在父组件中运行良好。但是不能在子组件中工作。如何解决这个问题?

{
    path: 'create',
    component: CreateComponent,
    canDeactivate: [ConfirmationGuard],
},
{
    path: ':id',
    component: ViewUserComponent,
    children: [
        {
            path: ':id',
            component: AddressComponent,
            canDeactivate: [ConfirmationGuard],
        },
    ],
    canDeactivate: [ConfirmationGuard],
},

'create' 工作正常,但地址组件不工作,因为它是子组件!

confirmationguard.ts:-

import { Component } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ConfirmLeaving } from './interface';

 export declare class ConfirmationGuard implements 
 CanDeactivate<ConfirmLeaving | Component> {

 canDeactivate(component: ConfirmLeaving | Component): Promise<boolean>;
 }

ConfirmationGuard 需要是一个实际的服务...换句话说,它必须是@Injectable,并且在模块中提供(或者您可以使用 providedIn: root)。

如果 AddressComponent 有一个模块,您可以在导入部分下的@NgModule 中导入它自己的模块,以确保您将导入它的所有导入、声明或提供程序