angular - Angular Auth Guard 未导航到新路由
问题描述
我的 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 方法中,我尝试在构造函数中注入一个 route:ActivatedRoute 并替换
this.router.navigateByUrl('/home');
和
this.router.navigate(['/home'], { relativeTo: this.route });
它有时似乎有效*,但其他时候却没有。所以我不确定是什么原因造成的。任何人都精通路由及其与 Auth Guard 的关系,或者知道为什么会发生这种情况?
解决方案
它不是逐行执行。将 return true 包装到 else 块中。
canLoad(route: Route, segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn !== true) {
this.router.navigateByUrl('/')
} else {
return true;
}
}