Проблема
Я использую кандеривацию guard in angular, чтобы предложить пользователю перед тем, как отступить от формы с неопасными изменениями. Он отлично работает для нормальных изменений маршрута (например, нажатие на ссылку), но это , когда пользователь нажимает кнопку Browser Back < /strong>. IS включен/редактировать с неспасенными изменениями.
[*] Нажимает кнопку «strong> broulser Back» [/b].
[*] диалог подтверждения export class YourFormComponent implements CanComponentDeactivate, OnInit, AfterViewInit {
hasUnsavedChanges = false;
// Implement the canDeactivate method
canDeactivate(): Observable | boolean {
if (!this.hasUnsavedChanges) {
return true;
}
const confirmLeave = window.confirm('You have unsaved changes. Leave anyway?');
return confirmLeave;
}
}
< /code>
route.ts
import { Routes } from '@angular/router';
import { YourFormComponent } from './your-form.component';
import { ConfirmLeaveGuard } from './confirm-leave.guard';
const routes: Routes = [
{
path: 'form',
component: YourFormComponent,
canDeactivate: [ConfirmLeaveGuard]
}
];
< /code>
concrim-leave.guard.ts
import { inject } from '@angular/core';
import { CanDeactivateFn } from '@angular/router';
import { Observable } from 'rxjs';
import { Location } from '@angular/common';
export interface CanComponentDeactivate {
canDeactivate: () => Observable | Promise | boolean;
}
export const ConfirmLeaveGuard: CanDeactivateFn = (component: any, currentRoute, currentState, nextState) => {
const location = inject(Location);
const result = component.canDeactivate();
// If it's a boolean value
if (typeof result === 'boolean') {
if (!result) {
location.replaceState(window.location.pathname); // Restore URL
}
return result;
}
// If it's an Observable or Promise
if (result instanceof Observable || result instanceof Promise) {
return new Promise(resolve => {
Promise.resolve(result).then(confirmed => {
if (!confirmed) {
location.replaceState(window.location.pathname); // Restore URL
}
resolve(confirmed);
});
});
}
return true;
};
< /code>
Я также пытался использовать местоположение. ценится.
Подробнее здесь: https://stackoverflow.com/questions/795 ... kips-route