简体   繁体   English

canActivate 中的 navigateByUrl

[英]navigateByUrl in canActivate

I see some example code here:我在这里看到一些示例代码:

https://medium.com/javascript-everyday/keep-data-in-the-state-object-during-navigation-in-angular-5657af156fb8 https://medium.com/javascript-everyday/keep-data-in-the-state-object-during-navigation-in-angular-5657af156fb8

The specific code is:具体代码为:

  canActivate(next: ActivatedRouteSnapshot, { url }: RouterStateSnapshot): boolean 
  {
       if (!this.authService.isLoggedIn) {
             this.router.navigateByUrl('/auth', { state: { redirect: url } });
       }

       return this.authService.isLoggedIn;
  }

What exactly will happen here if this.authService.isLoggedIn = false?如果 this.authService.isLoggedIn = false,这里到底会发生什么?

navigateByUrl is then called in this function, before this.authService.isLoggedIn is returned, how will this behave?然后在此 function 中调用 navigateByUrl,在返回 this.authService.isLoggedIn之前,这将如何表现? Will the function return "false" as value "immediately"? function 会“立即”返回“false”作为值吗? Or will CanActivate be "aborted" somehow by the navigateByUrl function?或者 CanActivate 会被 navigateByUrl function 以某种方式“中止”吗?

A bit tricky to explain, but it seems strange to return a value from a CanActivate function that is not relevant anymore... because you have navigated away from the page that was requested...解释起来有点棘手,但是从不再相关的 CanActivate function 返回一个值似乎很奇怪......因为您已经离开了请求的页面......

It will return false , but in addition it will redirect the user .它将返回false ,但另外它将重定向user

This is useful when you try to navigate to some routes where only the logged in user should be able to navigate.当您尝试导航到只有登录用户才能导航的某些路线时,这很有用。 So, if the user is not logged in you will probably redirect him to Login Page and return false .因此,如果用户未登录,您可能会将他重定向到Login Page并返回false When you return false , then current navigation will be cancelled.当您返回false时,当前导航将被取消。

Interface that a class can implement to be a guard deciding if a route can be activated. class 可以实现的接口,作为决定是否可以激活路由的守卫。 If all guards return true, navigation continues.如果所有守卫都返回 true,则导航继续。 If any guard returns false, navigation is cancelled.如果任何守卫返回 false,导航将被取消。

You can also return a UrlTree , and in that case the current navigation will be canceled and a new navigation will start.您还可以返回UrlTree ,在这种情况下,当前导航将被取消并开始新的导航。

If any guard returns a UrlTree, the current navigation is cancelled and a new navigation begins to the UrlTree returned from the guard.如果任何守卫返回一个 UrlTree,则当前导航被取消,并且新的导航开始到从守卫返回的 UrlTree。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM