Using Angular2, how to redirect to previous url before login redirect

前端 未结 4 1671
说谎
说谎 2020-12-31 03:29

Using Angular2 to create a single page app, I\'m intercepting unauthenticated user access to non-public routes in a custom RouterOutlet and redirecting them to

4条回答
  •  灰色年华
    2020-12-31 04:20

    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;
      }
      
    3. Redirect to that URL on successful authentication with using Router (e.g. in the login.component.ts). E.g. this._router.navigateByUrl(redirectUrl);

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

提交回复
热议问题