如果未保存更改,Angular 2/4 会阻止用户离开组件 [英] Angular 2/4 prevent user to leave component if changes not saved

查看:23
本文介绍了如果未保存更改,Angular 2/4 会阻止用户离开组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个界面,我用它来防止用户离开页面

I have this interface that i'm using to prevent the user to leave page

export interface ComponentCanDeactivate {
  canDeactivate: () => boolean;
}

@Injectable()
export class PendingChangesGuard implements CanDeactivate<ComponentCanDeactivate> {
  canDeactivate(component: ComponentCanDeactivate): boolean {
    return  component.canDeactivate() ?
     //code : //more code
  }
}

在我的一个组件中,我有以下代码

In one of my component i have the following code

export class DashboardComponent implements ComponentCanDeactivate{
  @HostListener('window:beforeunload')
  canDeactivate(): boolean {
    return !this.isDirty;
  }

我的问题是我的组件 -> (component: ComponentCanDeactivate) from PendingChangesGuard 始终为 null,所以我收到一条错误消息

My problem is that my component -> (component: ComponentCanDeactivate) from PendingChangesGuard is always null so i get an error saying

不能调用canDeactivate() of null

Cannot call canDeactivate() of null

我的路由中也有这个设置

I also have this setup in my routing

 path: 'dashboard',
        canDeactivate: [PendingChangesGuard],
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

谁能告诉我我做错了什么?

Can someone tell me what am i doing wrong?

推荐答案

延迟加载导致的问题

而不是在您的应用路由中使用它:

Instead of having this in your app routing:

path: 'dashboard',
        canDeactivate: [PendingChangesGuard], <-- causing issue
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'

您需要从应用路由中移除 canDeactive 并将其移动到模块路由中.

You need to remove the canDeactive from the app routing and move it to the module routing.

const routes: Routes = [
  {
    path: '',
    component: DashboardComponent,
    canDeactivate: [ PendingChangesGuard ]
  }

这篇关于如果未保存更改,Angular 2/4 会阻止用户离开组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆