角度:如果视图中的任何更改,请防止路线更改



如果我在视图中有一个形式(角)。当用户试图离开那里时,我希望出现一条确认消息。我该怎么做?

您可以使用Typescript(例如

)实现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 {}

来源:https://blog.thoughtram.io/angular/2016/07/18/guards-inguard-in-angular-2.html

CanDeactivate可以用于此。您需要将状态传递给canDeactivate可访问的服务。

如果您的网站需要阻止多个页面的路由更改,我想使用此服务可能很方便:

import { Injectable } from '@angular/core';
import { CanActivateChild } from '@angular/router';

@Injectable()
export class NavPreventerService implements CanActivateChild {
  locks: any = {};
  constructor() {
    // Bonus: If necessary also prevent closing the window:
    window.addEventListener('beforeunload', (event) => {
      if (this.hasRoutingLocks()) {
        event.preventDefault();
        event.returnValue = '';
      }
    });
  }
  canActivateChild() {
    if (this.hasRoutingLocks()) {
      if (confirm('Leave site?')) {
        this.removeAllRoutingLocks();
        return true;
      }
      return false;
    }
    return true;
  }
  setRoutingLock(key: string) {
    this.locks[key] = true;
  }
  removeRoutingLock(key: string) {
    delete this.locks[key];
  }
  removeAllRoutingLocks() {
    this.locks = {};
  }
  hasRoutingLocks(): boolean {
    return !!Object.keys(this.locks).length;
  }
}

需要防止导航时,然后在组件调用

this.navPreventer.setRoutingLock('quiz-form');

您的应用程序路由文件应该是这样的:

export const appRoutesLocal: Routes  = [
  {path: '', canActivateChild: [NavPreventerService], children: [
    {path: '', component: HomePageComponent},
  ]}
];

在我的示例网站中,用户应在导航到其/她/她的个人详细信息 page。对于所有其他页面,用户不需要安全引脚。在安全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]); 
  } 
}