首页 > 解决方案 > 开始路由之前的Angular 6调用后端api

问题描述

我有一个 Angular 6 应用程序。新用户需要进行快速设置才能使用该应用程序。

我正在使用后端 api 检查用户状态并查看用户是否已完成初始设置。

我正在调用这个 api,AppComponent::ngOnInit如果LoginConponent::ngOnInit用户正在访问/或未经授权,这工作正常,因为在外部登录后用户将被重定向到/login.

/profile但是,如果用户在登录后但在完成初始设置之前手动输入 url ,用户将被重定向到/profile页面并在后端 api 检查其状态并最终重定向到页面时看到页面一秒钟/quick-setup

有没有办法在应用程序启动时自动停止 Angular 路由?所以我可以手动完成吗?

我不需要也不想在每次路线更改时检查这一点,只需在应用程序启动时!

我可以以某种方式使用Resolve它吗?

我已经必须AuthGuard检查身份验证状态,但这将在每次路线更改时检查,这不是我想要的

标签: angularroutingangular-router

解决方案


好的,这就是我为完成这项工作所做的工作。

首先进入app.component

  ngOnInit(): void {    
    //always go to login page to authenticate and then redirect to the requested url
    this.authService.navigateToLogin();
  }
  navigateToLogin() {
    if (!Util.checkUrl('/logout') && !Util.checkUrl('/signup'))
      this.router.navigate(['/login'], { skipLocationChange: true });
  }

login.component中,将 cookie 存储location.pathname在 cookie 中,以便登录后重定向到它

  ngOnInit() {
    if (!Util.checkUrl('/login') && !Util.checkUrl('/', true) && !Util.checkUrl('/#')) {
      this.cookieService.set(COOKIE_LOGIN_REDIRECT, location.pathname, 3600, '/');
    }

    this.authService.verify();
  }

this.authService.verify();检查后端以查看用户是否正常,然后重定向到存储在 cookie 中的位置。

    let redirect = this.cookieService.get(COOKIE_LOGIN_REDIRECT);
    if (redirect) {
      this.cookieService.delete(COOKIE_LOGIN_REDIRECT, '/');
      redirect = redirect.replace(environment.baseHref, '');
      return this.router.navigateByUrl(redirect);
    }

推荐阅读