角度2/4防止用户在未保存更改的情况下离开组件 [英] Angular 2/4 prevent user to leave component if changes not saved

查看:65
本文介绍了角度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;
  }

我的问题是PendingChangesGuard中的我的组件->(组件:ComponentCanDeactivate)始终为空,所以我得到一个错误提示

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

不能调用null的canDeactivate()

Cannot call canDeactivate() of null

我的路由中也有此设置

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

有人可以告诉我我在做什么错吗?

Can someone tell me what am i doing wrong?

推荐答案

此问题是由延迟加载引起的

The issue was caused by lazy loading

不要在您的应用程序路由中使用它:

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 ]
  }

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

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