Angular 5 - 登录后重定向到先前的页面

18

Angular 5 登录后重定向到之前的页面。

当我手动输入URL时,如果未登录,它会重定向到登录页面,但登录后,应该重定向到输入的URL,但现在我只能使用以下方式重定向到主页:

this.router.navigate(['/homepage']);

有一些想法吗?

5个回答

39

当你使用守卫重定向到登录页面时,可以将源URL放在 queryParams 中,如下所示:

canActivate(next: ActivatedRouteSnapshot,
            state: RouterStateSnapshot) {
    if (this.authService.isAuthenticated()) {
        return true;
    } else {
        console.log('Could not authenticate');
        this.router.navigate(['login'],{queryParams:{'redirectURL':state.url}});
        return false;
    }
}

登录后,您可以从查询参数中获取原始页面网址:

let params = this.route.snapshot.queryParams;
    if (params['redirectURL']) {
        this.redirectURL = params['redirectURL'];
    }

...

if (this.redirectURL) {        
    this.router.navigateByUrl(this.redirectURL,)
        .catch(() => this.router.navigate(['homepage']))
} else {

    this.router.navigate(['homepage'])
}

由于我是Angular的新手,你为重定向编写的最后一段代码将出现在登录API的subscribe部分中,对吗? - Barefaced Bear

6
您可以在进入主页之前发送URL并在那里使用它。
@Component({ ... })
class SomePageComponent {
  constructor(private route: ActivatedRoute, private router: Router) {}
  checkLogin() {
    if (!this.auth.loggedIn()) {
      this.router.navigate(['/homepage`], { queryParams: { redirectTo: this.route.snapshot.url } });
    }
  }
}

那么在您的登录组件中,您可以像这样访问查询参数。
@Component({...})
class LoginComponent {
  constructor(private router: Router, private route: ActivatedRoute) {}

  backToPreviousPage() {
    this.router.navigate(
         [this.route.snapshot.queryParams.get('redirectTo')]
    );
  }
}

5
自Angular 7.2起,您可以使用状态对象在跳转到登录页面之前设置最后一个URL:
@Component({ ... })
class SomePageComponent {
  constructor(private router: Router) {}

  checkLogin() {
    if (!this.auth.loggedIn()) {
      this.router.navigate(['login'], { state: { redirect: this.router.url } });
    }
  }
}

@Component({...})
class LoginComponent {
  constructor(private router: Router) {}

  backToPreviousPage() {
    const { redirect } = window.history.state;

    this.router.navigateByUrl(redirect || '/homepage');
  }
}

4

对我来说,查询参数并不起作用,因为如果用户去登录,然后进入注册路由,所以您需要保留查询参数。但是,如果在登录之前有更多步骤,或者用户刷新页面,或者地铁上的互联网不好或发生其他事情导致他失去了参数,那么他将被重定向到谁知道哪里……但是,如果您将所需的URL设置为重定向到localStorage,并且在登录/注册/其他步骤之后,您可以将其重定向到以前从localStorage中删除字符串所需的URL。

// needed page
localStorage.setItem('redirectTo', this.router.url);
this.router.navigateByUrl('/login');

// login/signup/else step page
success => {
  const redirect = localStorage.getItem('redirectTo');
  if (redirect) {
    localStorage.removeItem('redirectTo');
    this.router.navigate(redirect);
  } else {
    this.router.navigate('defaultpath');
  }
}

3

authService url: string中声明变量,并在您的auth.gaurd.ts中使用该变量。

      this.authService.redirectUrl = url;
      this.navigateTo("/login");
      return false;

接下来在 login.ts 文件中编写代码。

          if (this.authService`enter code here`.redirectUrl) {
            this.router.navigateByUrl(this.authService.redirectUrl);
          } else {
            this.router.navigateByUrl("/home");
          }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接