大家好,我是 Angular 的新手,并使用以下教程链接学习这些东西。由于某种原因, canDeactivate 路由保护似乎不起作用。当我尝试检查很多事情但没有任何工作时,任何帮助将不胜感激。我有最新的角度 CLI,并且我的代码中没有错误,并且由于某种原因,在路线更改期间根本没有调用 canDeactivate 函数。
我在 CreateEmployee 路线上应用该功能,因此当我为 createEmployee 填写表格并尝试导航到不同的路线时,它应该会启动。
create-employee-component.html:在这里,我的表单元素很少
<form #employeeForm = "ngForm" (ngSubmit)="saveEmployee()" [ngClass]="{'was-validated': employeeForm.submitted}" novalidate>
创建员工组件.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Department } from '../models/department.model';
import { BsDatepickerConfig } from 'ngx-bootstrap/datepicker';
import { Employee } from '../models/employee.model';
import { EmployeeService } from './employee.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-create-employee',
templateUrl: './create-employee.component.html',
styleUrls: ['./create-employee.component.css']
})
export class CreateEmployeeComponent implements OnInit {
@ViewChild('employeeForm') public createEmployeeForm: NgForm;
datePickerConfig: Partial<BsDatepickerConfig>;
previewPhoto = false;
创建员工可以停用guard.service.ts
import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { CreateEmployeeComponent } from './create-employee.component';
@Injectable()
export class CreateEmployeeCanDeactivateGuardService implements CanDeactivate<CreateEmployeeComponent>{
canDeactivate(component: CreateEmployeeComponent): boolean{
alert("HJEJJEJEJ");
if(component.createEmployeeForm.dirty)
{
return confirm('Are you sure you want to discard your changes?');
}
return true;
}
}
应用程序路由.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ListEmployeesComponent } from './employees/list-employees.component';
import { CreateEmployeeComponent } from './employees/create-employee.component';
import { CreateEmployeeCanDeactivateGuardService } from './employees/create-employee-can-deactivate-guard.service';
const routes: Routes = [
{path: 'list', component: ListEmployeesComponent},
{
path:'create',
component: CreateEmployeeComponent,
canDeactivate: [CreateEmployeeCanDeactivateGuardService]
},
{path: '', redirectTo:'/list', pathMatch:'full'}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
providers: [CreateEmployeeCanDeactivateGuardService]
})
export class AppRoutingModule { }
根据我在 StackOverflow 上找到的其他一些答案,我觉得一切都是正确的。请让我知道我在这里做错了什么。我也在这里发布了我的代码。