angular - 为什么 CanDeactivate Guard 无法读取我的组件中的方法?

标签 angular angular-router-guards

我正在懒惰地加载我的路线。我正在尝试按照文档使用 CanDeactivate 但似乎守卫无法读取组件的属性或方法。

这是我的守护者,

@Injectable()
export class CanDeactivateGuard implements CanDeactivate<PatientRegistrationFormComponent> {
  constructor() {}
  canDeactivate(component: PatientRegistrationFormComponent) {
    return component.isChangesSaved();
  }
}

isChangesSaved() 是组件内部的一个方法。

public isChangesSaved(): Observable<boolean> {
    if (this.isDirtyForm()) {
      return this.confirmService.confirmUnsavedChanges();
    }
    return of(false);
  }

这是错误,

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'isChangesSaved' of null TypeError: Cannot read property 'isChangesSaved' of null at CanDeactivateGuard.push../src/app/core/database/database-cores/registry-core/guards/patient-registration.guard.ts.CanDeactivateGuard.canDeactivate

这是我的模块(延迟加载)

@NgModule({
  imports: [
    CommonModule,
    RegistryRoutingModule,
    ReactiveFormsModule,
    FormsModule,
  ],
  declarations: [
    RegistryContainerComponent,
    RegistryHomeComponent,
    PatientRegistrationFormComponent, // component of interest ….
  ],
  exports: [PatientRegistrationFormComponent],
  schemas: [NO_ERRORS_SCHEMA],
  providers: [
    …fromGaurds.guards,  // all my guards are loaded here….
    { provide: ErrorStateMatcher, useClass: ShowOnDirtyErrorStateMatcher },
    ToastService,
  ],
})
export class RegistryModule {}

这是我的路由模块

const routes: Routes = [
  {
    path: '',
    component: RegistryContainerComponent,
    children: [
      {
        path: '',
        component: RegistryHomeComponent,
      },
      {
        path: 'patientregistration',
        component: PatientRegistrationFormComponent,
        canDeactivate: [fromGaurds.CanDeactivateGuard],

        children: [
          {
            path: '',
            component: PatientRegistrationFormComponent,
             canActivate: [fromGaurds.PatientRegistryGuard],
            canDeactivate: [fromGaurds.CanDeactivateGuard],
          },
          {
            path: ':id',
            component: PatientRegistrationFormComponent,
            canActivate: [fromGaurds.PatientRegistryRecordGuard],
            canDeactivate: [fromGaurds.CanDeactivateGuard],
          },
        ],
      },
    ],
  },
];
@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
export class RegistryRoutingModule {}

这是接口(interface)的错误还是错误的实现?

更新

我厌倦了将防护添加到延迟加载模块中。 这是上面提到的子模块 RegistryModule 的父模块,

const dbRoutes: Routes = [
  {
    path: '',
    component: DbHomeComponent,
    data: { preload: true },
    canDeactivate: [fromGaurds.CanDeactivateGuard],
    children: [
      { path: '', component: UsersDashboardComponent },
      {
        path: 'registry',
        canActivate: [RoleGuardService],
        data: { expectedRole: { roles: ['reg'] } },
        loadChildren: '../database-cores/registry-core/modules/registry.module#RegistryModule',
      },
      {
        path: 'cloudstorage',
        canActivate: [RoleGuardService],
        loadChildren:
          '../database-cores/cloud-storage-core/modules/cloud-storage.module#CloudStorageModule',
      },
    ],
  },
];
@NgModule({
  imports: [RouterModule.forChild(dbRoutes)],
  exports: [RouterModule],
})
export class DbRoutingModule {}

@NgModule({
  declarations: [
    DbHeaderComponent,
    DbFooterComponent,
    DbHomeComponent,
    UsersDashboardComponent,
  ],
  imports: [

    }),
  ],
  exports: [],
  providers: [
    ...fromGaurds.guards,
    MDBSpinningPreloader,
    ToastService,
    DirectoryService,
  ],
  schemas: [NO_ERRORS_SCHEMA],
})
export class DbModule {}

最佳答案

我修改了你的stackblitz重现该问题。问题的核心是同一组件的同一个停用防护装置被触发两次。第二次触发时,该组件已被停用并且不再存在,因此会出现错误。

有问题的代码位于RegistryRoutingModule 中。父路由'patentregistration'和子路由''同时处于事件状态,并使用相同的守卫。如果你移除其中一个防护装置,它应该可以工作。根据您的用例,您可以从父级或子级中删除守卫,但是考虑到守卫将级联,您可以从所有子级中删除。

const routes: Routes = [
  {
    path: '',
    component: RegistryContainerComponent,
    children: [
      {
        path: '',
        component: RegistryHomeComponent,
      },
      {
        path: 'patientregistration',
        component: PatientRegistrationFormComponent,
        canDeactivate: [fromGaurds.CanDeactivateGuard],

        children: [
          {
            path: '',
            canActivate: [fromGaurds.PatientRegistryGuard]
          },
          {
            path: ':id',
            canActivate: [fromGaurds.PatientRegistryRecordGuard]
          },
        ],
      },
    ],
  },
];

关于angular - 为什么 CanDeactivate Guard 无法读取我的组件中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923699/

相关文章:

angular - 使用 Angular 11 自定义页面权限

android - 如何在文本字段外触摸后隐藏键盘?

Angular2 全局变量可观察

无法找到 Angular Material MatTableDataSource

angular - 当用户在 angular13 中没有任何权限时将用户重定向到主页

Angular 6 基于角色的根 url 路由

angular - 路由守卫导致错误的路由导航行为

angular - 当用户路由到不同的页面时,setTimeout 继续,如何在 Angular typescript 中清除超时?

javascript - Angular Component 的 CSS 封装是如何工作的?