且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Angular2,如何在登录重定向前重定向到上一个 url

更新时间:2023-10-25 23:37:04

  1. 使用身份验证保护(实现 CanActivate) 以防止未经身份验证的用户.请参阅带有示例的官方文档此博客.
  2. 使用 RouterStateSnapshot用于捕获请求的 URL 的身份验证保护.

  1. Use Auth Guards (implements CanActivate) to prevent unauthenticated users. See official documentation with examples and this blog.
  2. Use RouterStateSnapshot in the auth guard to capture the requested URL.

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) 
{
    // keep the attempted URL for redirecting
    this._loginService.redirectUrl = state.url;
}

  • 使用 路由器(例如在 login.component.ts 中).例如.this._router.navigateByUrl(redirectUrl);

  • Redirect to that URL on successful authentication with using Router (e.g. in the login.component.ts). E.g. this._router.navigateByUrl(redirectUrl);

    附言@MichaelOryl 和 @Vitali 的建议可行,但我的方式更符合 Angular2 最终版本.

    P.S. Suggestions of @MichaelOryl and @Vitali would work, but my way is more aligned with Angular2 final release.