Angular:如果在视图中进行了任何更改,则阻止路由更改

时间:2016-11-24 11:52:20

标签: angular

如果我在视图中有一个表单(Angular)。当用户尝试离开那里时,我想要显示确认消息。我怎么能这样做?

4 个答案:

答案 0 :(得分:20)

您可以使用

等打字稿来实现canDeactivate



import {Injectable, Inject} 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]},
&#13;
&#13;
&#13;

答案 1 :(得分:3)

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

答案 2 :(得分:1)

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

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},
  ]}
];

答案 3 :(得分:0)

在“我的示例”网站中,用户在导航至他/她的“ <个人>个人详细信息”页面时,应验证安全密码。对于其他所有页面,用户不需要安全图钉。成功通过安全密码验证后,只有他才能浏览至“个人详细信息”,否则用户应位于同一页面。

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]); 
  } 
}