Подтвердить что ты не робот

Угловое: предотвращение изменения маршрута, если любые изменения, сделанные в представлении

Если у меня есть форма в представлении (Угловая). Когда пользователь пытается перейти оттуда, и я хочу, чтобы появилось подтверждающее сообщение. Как я могу это сделать?

4b9b3361

Ответ 1

Вы можете реализовать canDeactivate, используя машинопись

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { ViewthatyouwantGuard } from './path to your view';

@Injectable()
export class ConfirmDeactivateGuard implements CanDeactivate<ViewthatyouwantGuard> {
    
    canDeactivate(target: ViewthatyouwantGuard) {
        if (target.hasChanges) {
            return window.confirm('Do you really want to cancel?');
        }
        return true;
    }

}

// hasChanges - function in 'ViewthatyouwantGuard' which will return true or false based on unsaved changes

// And in your routing file provide root like 
{path:'rootPath/', component: ViewthatyouwantGuard, canDeactivate:[ConfirmDeactivateGuard]},

// Last but not least, also this guard needs to be registered accordingly:
@NgModule({
    ...
    providers: [
        ...
        ConfirmDeactivateGuard
    ]
 })
 export class AppModule {}

Ответ 2

CanDeactivate можно использовать для этого. Вам необходимо передать статус службе, доступной для canDeactivate.

Ответ 3

В моем примере сайта пользователь должен проверить безопасный пин-код при переходе на свою личную страницу. Для всех остальных страниц пользователю не нужен безопасный пин-код. После успешной проверки PIN-кода только он должен перейти в "Личные данные", в противном случае пользователь должен находиться на той же странице.

private routerChangeListener() {
  this.router.events.subscribe(event => {
    if (event instanceof NavigationStart) {
      this.isPersonalDetailsNavigation(event.url);
    }
   });
}

private verfiyIsNavigatingToMedication(url: string) {
   url = url.replace('/', '');
   if (url === 'personal-details') {
    showPinVerficationPopup();
   } else {
    console.log('This Is Not Personal Details Page Navigation');
   }
}

private showPinVerficationPopup() {
  if(verificationSuccess) {
    // This Will Navigate to Personal Details Page
    this.router.navigate(['personal-details']); 
  } else {
    // This Will Prevent Navigation
    this.router.navigate([this.router.url]); 
  } 
}