【问题标题】:Angular Auth Guard is not navigating to new RouteAngular Auth Guard 未导航到新路由
【发布时间】:2021-07-15 04:00:36
【问题描述】:

我的 Auth Guard 在尝试在不登录的情况下搜索 URL 时按预期工作。但是,登录时,URL 中的导航不会改变,并且用户不会被路由到正确的页面。但是,它是*运行正确的登录方法以重新路由到预期的页面,所以我不确定为什么它不是,或者在使用 Auth Guard 时我是否缺少某种基本规则。我也在使用延迟加载的主页,以防与它有关...

我的身份验证...

import { Injectable } from '@angular/core';
import { CanLoad, Route, Router, UrlSegment } from '@angular/router';

import { Observable } from 'rxjs';

import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanLoad {
  constructor(
    private authService: AuthService, 
    private router: Router
  ) {}

  canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/')
    }
    return true;
    
  }
  
}

我的登录方法。注意其中的 console.log()。它在使用 Auth Guard 时运行,证明它应该可以工作......

signIn(email: string, password: string) {
    return this.afAuth.signInWithEmailAndPassword(email, password)
      .then((result) => {
        this.ngZone.run(() => {
          this.isLoggedIn$.next(true);
          console.log('Sign in method...');
          this.router.navigateByUrl('/home');
        });
        this.SetUserData(result.user);
      }).catch((error) => {
        window.alert(error.message)
      })
  }

我的 Getter 方法为 Auth Guard 返回一个布尔值...

get isLoggedIn(): boolean {
    const user = JSON.parse(localStorage.getItem('user'));
    return (user !== null) ? true : false;
  }

我的懒加载路线...

const routes: Routes = [
    {
      path: 'home', 
      canLoad: [AuthGuard], 
      loadChildren: () => 
        import('./home/home.module').then(m => m.HomeModule)
    }, 
    {
        path: 'onTheirWay', 
        canLoad: [AuthGuard], 
        loadChildren: () => 
            import('./on-their-way/on-their-way.module').then(m => m.OnTheirWayModule)
    }, 
    {
        path: 'preorders', 
        canLoad: [AuthGuard], 
        loadChildren: () => 
            import('./preorders/preorders.module').then(m => m.PreordersModule)
    }
  ];

更新

我也应该澄清一下。如果我删除了 Routes 文件中的 Auth Guard,登录方法将导航到正确的页面。它与 Auth Guard 有关。添加如上所示的代码会影响导航运行。

更新

这是我的身份验证组件的路由文件,其中包括“/”路径...

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { SigninComponent } from './signin/signin.component';
import { SignoutComponent } from './signout/signout.component';
import { SignupComponent } from './signup/signup.component';

const routes: Routes = [
  { path: 'signout', component: SignoutComponent }, 
  { path: 'signup', component: SignupComponent }, 
  { path: '', component: SigninComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthRoutingModule { }

更新

在 signIn 方法中,我尝试在构造函数中注入一个路由:ActivatedRoute 并替换

this.router.navigateByUrl('/home'); 

this.router.navigate(['/home'], { relativeTo: this.route });

它有时似乎有效*,但有时却无效。所以我不确定是什么原因造成的。任何人都精通路由及其与 Auth Guard 的关系,或者知道为什么会发生这种情况?

【问题讨论】:

  • 你有没有考虑过pathMatch:'full'你的空路由?见angular.io/api/router/…
  • 其实我现在刚试过,没用。导航也有同样的问题。
  • AuthGuard 中,如果您将this.router.navigateByUrl('/') 替换为console.log,它会被命中吗?
  • 另外,你为什么在这里使用ngZone
  • 如果您手动导航到/home 是否有效?

标签: angular auth-guard


【解决方案1】:

在重定向后执行return false

 canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/');
      return false; // <-----------------------
    }
    return true;
    
  }

【讨论】:

  • 不,它仍然有同样的问题。服务中的登录方法正在运行,但它没有运行导航代码。我也没有任何其他导航代码可以覆盖它。所以不确定是什么阻止了该方法中的重新路由。
【解决方案2】:

不是逐行执行。将 return true 包装到 else 块中。

canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean  {
    if (this.authService.isLoggedIn !== true) {
      this.router.navigateByUrl('/')
    } else {
      return true;
    }
  }

【讨论】:

  • 这似乎也不起作用。某些东西正在阻止登录方法中的路线导航运行。运行之前的 console.log() 行。我什至尝试在 Auth Guard return true 块中添加一条路线导航线,但这似乎也不起作用。
  • 你真的有/路线吗?你的 const routes: Routes = [] 没有它。要么声明它,要么从 / { path: '', redirectTo: 'home', pathMatch: 'full'}, 添加一个重定向
  • 我有一个“/”路由指向我的登录组件。我已经更新了上面的问题以显示我的 auth-routes 文件。在我添加 Auth Guard 之前,我的 app-routes 和我的 auth-routes 一直运行良好,所以我不确定它到底在做什么来中断导航。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多