1。为 CanDeactivate Guard 创建服务
首先,您必须创建一个接口来声明canDeactivate 方法,并使用此接口创建一个充当canDeactivate 守卫的服务。该服务将定义canDeactivate 方法如下:
deactivate.guard.ts:
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
export interface CanComponentDeactivate {
canDeactivate(): boolean;
}
@Injectable()
export class DeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
canDeactivate(component: CanComponentDeactivate): boolean {
/*
The return value would be true, unless the canActivate function,
defined on the component returns false,
in which case the function will open a Dialog Box,
to ask if we want to stay on the page or leave the page.
*/
if (component.canDeactivate()) return true;
else return confirm('You have unsaved changes!') ? true : false;
}
}
接口声明了canDeactivate 方法,其返回类型为布尔值。在服务代码中,我们使用组件实例调用了canDeactivate方法。
2。在应用路由模块中配置 CanDeactivate Guard 服务
app.module.ts:
import { CanDeactivateGuard } from './can-deactivate-guard.service';
------
@NgModule({
------
providers: [
CanDeactivateGuard
]
})
export class AppRoutingModule { }
3。在您的组件中创建 canDeactivate() 方法
formComponent.ts:
import { Component, HostListener } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { CanComponentDeactivate } from 'src/app/deactivate.guard';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.scss']
})
export class FormComponent implements CanComponentDeactivate {
saved: boolean;
form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
name: ['']
});
}
/* Prevent page reloading */
@HostListener('window:beforeunload', ['$event'])
canReload(e) {
if (!this.canDeactivate()) e.returnValue = true;
}
submit = () => this.saved = true;
canDeactivate = () => this.saved || !this.form.dirty;
}
4。在路由模块中为组件路由添加 CanDeactivate Guard
您需要添加我们的 CanDeactivate 守卫。即使用 canDeactivate 属性将路由模块中的组件路由停用。
app-routing.module.ts:
const routes: Routes = [
{
path: 'home',
component: FormComponent,
canDeactivate: [DeactivateGuard]
},
{ path: 'next', component: NextComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' }
];
您不妨考虑将数据存储在服务中,因为这可能是更好的选择。