Ответ 1
Я немного наткнулся на этот вопрос после факта, но я надеюсь помочь кому-нибудь еще приехать сюда.
Основным кандидатом на решение является служба охраны маршрута.
Смотрите здесь для объяснения: https://angular.io/guide/router#candeactivate-handling-unsaved-changes
Соответствующая часть (почти дословно скопированная) - это реализация:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { CanDeactivate,
ActivatedRouteSnapshot,
RouterStateSnapshot } from '@angular/router';
import { MyComponent} from './my-component/my-component.component';
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<MyComponent> {
canDeactivate(
component: MyComponent,
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | boolean {
// you can just return true or false synchronously
if (expression === true) {
return true;
}
// or, you can also handle the guard asynchronously, e.g.
// asking the user for confirmation.
return component.dialogService.confirm('Discard changes?');
}
}
Где MyComponent
- ваш пользовательский компонент, а CanDeactivateGuard
будет зарегистрирован в вашем AppModule
в разделе провайдеров и, что более важно, в вашей конфигурации маршрутизации в свойстве массива canDeactivate
:
{
path: 'somePath',
component: MyComponent,
canDeactivate: [CanDeactivateGuard]
},