Angular4路由:绕过Route Guard进行强制导航

mas*_*onk 5 angular angular4-router

当我的用户在屏幕上进行肮脏的更改时,我会设置一个路由防护,以在他们尝试离开时提示他们保存或丢弃。

但是,如果由于不活动而将其注销,则我想强制导航并绕过路由保护程序(通过放弃对其所做的更改),以确保其屏幕为空白。

我如何绕过路线警卫?

Ken*_*eth 9

下面介绍了如何在每次导航的基础上强制绕过。就我而言,在用户提交包含帐户信息的表单后,我导航回帐户仪表板。

理想情况下,您会检查表单中是否有未保存的更改,并据此绕过,但我的表单还没有该功能。

表单组件:

this.router.navigateByUrl('/', { state: { bypassFormGuard: true } })
Run Code Online (Sandbox Code Playgroud)

路由器守卫:

@Injectable()
export class ExitFormGuard implements CanDeactivate<ComponentCanDeactivate> {

   constructor(private router: Router) {}

   canDeactivate(component: ComponentCanDeactivate): boolean | Observable<boolean> {
      if (this.router.getCurrentNavigation()?.extras?.state?.bypassFormGuard) {
         return true
      }

      // perform normal checks
   }
}

Run Code Online (Sandbox Code Playgroud)


Aak*_*ain 5

我的解决方案如下:

logout成功注销后,我的方法将应用程序重定向到/login路由:

@Injectable
export class AuthService {
  // ...
  logout () {
    // do logout
    this.router.navigate(['/login']);
  }
}
Run Code Online (Sandbox Code Playgroud)

我的警卫如下:

@Injectable
export class DiscardChangesGuard implements CanDeactivate<MyComponent> {

  canDeactivate(component: MyComponent, currentRoute: ActivatedRouteSnapshot,
                currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): Observable<boolean> | boolean {

    if (nextState.url === '/login') {
      return true; // bypass checks if we are trying to go to /login
    }

    // perform regular checks here
  }
}
Run Code Online (Sandbox Code Playgroud)


mas*_*onk 1

我的目标是绕过路线守卫而不触及应用程序中的每个路线守卫,但我无法做到这一点。最终我创建了一个新的RouteBypassService注入到每个路线守卫中。 RouteBypassServiceimplements shouldBypass,如果路由防护应允许出于某些覆盖带外原因(例如授权)进行导航,则返回 true。在我的例子中,shouldBypass如果没有用户登录,则返回 true。(他们注销后,无论如何我们都会让他们离开屏幕)。

这并不理想,因为路线防护的每个作者都必须记住添加旁路,但这并不是非常令人纠结。