有什么方法可以防止损坏角度组件

有什么方法可以防止损坏角度组件

本文介绍了有什么方法可以防止损坏角度组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道在angular中有一个ngOnDestroy()方法可以在销毁组件时运行,但是我想知道有什么方法可以防止销毁它吗?

We know that there is a method ngOnDestroy() in angular which runs on destroying a component but I want to know that is there any way to prevent it from destroying?

推荐答案

CanDeactivate 防护可以访问活动组件的实例,因此您可以实现 hasChanges()检查是否有更改,并在离开前有条件地要求用户确认.在下面的示例中, CanDeactivateComponent 实现了方法 hasChanges(),该方法返回一个布尔值,该值指示组件是否检测到任何更改. CanDeactivate 保护的实现类似于 CanActivate 保护的实现(您可以创建一个函数或实现 CanDeactivate 接口的类):

The CanDeactivate guard has access to the instance of the active component, so you can implement a hasChanges() that check if there have been changes and conditionally ask for the user confirmation before leave.In the following example the CanDeactivateComponent implements the methods hasChanges() that returns a boolean value indicating if the components has detected any changes.The implementation of CanDeactivate guard is similar to the CanActivate guard implelementaion (you can create a function, or a class that implements the CanDeactivate interface):

import { CanDeactivate } from '@angular/router';
import { CanDeactivateComponent } from './app/can-deactivate';

export class ConfirmDeactivateGuard implements CanDeactivate<CanDeactivateComponent>
{
  canDeactivate(target: CanDeactivateComponent)
  {
    if(target.hasChanges()){
      return window.confirm('Do you really want to cancel?');
    }
    return true;
  }
}

尽管这是一个非常简单的实现, CanDeactivate 使用泛型,所以您需要指定要停用的组件类型.

Even though, this is a very trivial implementation, CanDeactivate uses a generic, so you need to specify what component type you want to deactivate.

在组件的Angular路由器中:

In the Angular router of the component:

{
  path: '',
  component: SomeComponent,
  canDeactivate: [ConfirmDeactivateGuard]
}

最后,与Angular上的所有其他服务一样,该防护程序需要进行相应的注册:

Last, like all other services on Angular, this guard needs to be registered accordingly:

@NgModule({
  ...
  providers: [
    ...
    ConfirmDeactivateGuard
  ]
})
export class AppModule {}

您可以有多个保护单个路径的防护,这可以帮助您实现复杂的用例,其中需要一连串的不同检查.

You can have multiple guards protecting a single route, which helps you implementing sophisticated use cases, where a chain of different checks is needed.

这篇关于有什么方法可以防止损坏角度组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:36