Я перехожу по ссылке с: https://www.concretepage.com/angular-2/angular-candeactivate-guard-example, и в моем реальном приложении ничего не работает. У меня есть код ниже.
AppModule
@NgModule({
declarations: [
AppComponent,
TemplateComponent,
HeaderComponent,
FooterComponent,
SidebarComponent
],
imports: [
BrowserModule,
HttpClientModule,
AppRoutingModule,
FormsModule
],
providers: [DirectAccessGuard, PendingChangesGuard, DialogService],
bootstrap: [AppComponent]
})
export class AppModule { }
DialogService
import { Injectable } from '@angular/core';
import 'rxjs/add/observable/of';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class DialogService {
confirm(message?: string): Observable<boolean> {
const confirmation = window.confirm(message || 'Are you sure?');
return Observable.of(confirmation);
}
}
AppRoutingModule
const routes: Routes = [
{
path: '',
component: SidebarPageLayoutComponent,
children: [
..........
..........
{
path: 'employee/:programId',
canActivate: [DirectAccessGuard],
canDeactivate: [PendingChangesGuard],
pathMatch: 'full',
loadChildren: './employee/employee.module#EmployeeModule'
},
......
.........
]
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
PendingChangesGuard
import { CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable, HostListener } from '@angular/core';
import { Observable } from 'rxjs';
import { ProgramComponent } from '../employee/employee.component';
import { DialogService } from '../services/dialog.service';
export interface ComponentCanDeactivate {
canDeactivate: () => boolean | Observable<boolean>;
}
@Injectable()
export class PendingChangesGuard implements CanDeactivate<EmployeeComponent> {
constructor(private dialogService: DialogService) { }
canDeactivate(component: EmployeeComponent, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
const url: string = state.url;
console.log('Url: ' + url);
if (!component.isUpdating && component.form.dirty) {
component.isUpdating = false;
return this.dialogService.confirm('Discard changes for Country?');
}
return true;
}
}
ПРИМЕЧАНИЕ: я использую управляемые шаблоном формы и PendingChangesGuard
метод класса canDeactivate(component: CanComponentDeactivate...)
, где component
переменная всегда равна нулю