问题描述
My Auth Guard 正在按预期工作,尝试在未登录的情况下搜索 URL。但是,登录时,URL 中的导航不会更改,并且用户不会被路由到正确的页面。但是,它运行正确的登录方法以重新路由到预期页面,所以我不确定为什么不是,或者在使用 Auth Guard 时我是否缺少某种潜在规则。我也在使用延迟加载的主页,以防万一与它有关...
我的身份验证卫士...
us
我的登录方法。注意其中的 console.log()。它在使用 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;
}
}
我的 Getter 方法为 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)
})
}
我的懒加载路由...
get isLoggedIn(): boolean {
const user = JSON.parse(localStorage.getItem('user'));
return (user !== null) ? true : false;
}
更新
我也应该澄清一下。如果我去掉 Routes 文件中的 Auth Guard,登录方法会导航到正确的页面。它与Auth Guard有关。添加如上所示的代码会影响导航运行。
更新
这是我的 Auth 组件的路由文件,其中包含一个“/”路径...
const routes: Routes = [
{
path: 'home',canLoad: [AuthGuard],loadChildren: () =>
import('./home/home.module').then(m => m.HomeModule)
},{
path: 'onTheirWay',loadChildren: () =>
import('./on-their-way/on-their-way.module').then(m => m.OnTheirWayModule)
},{
path: 'preorders',loadChildren: () =>
import('./preorders/preorders.module').then(m => m.PreordersModule)
}
];
更新
在signIn方法中,我尝试在构造函数中注入一个路由:ActivatedRoute并替换
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 { }
与
this.router.navigateByUrl('/home');
它有时似乎有效*,但有时却不起作用。所以我不确定是什么原因造成的。任何人都了解路由及其与 Auth Guard 的关系,或者知道为什么会发生这种情况?
解决方法
在重定向后执行 return false
。
canLoad(route: Route,segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn !== true) {
this.router.navigateByUrl('/');
return false; // <-----------------------
}
return true;
}
,
它不是逐行执行的。将 return true 包装到 else 块中。
canLoad(route: Route,segments: UrlSegment[]): Observable<boolean> | Promise<boolean> | boolean {
if (this.authService.isLoggedIn !== true) {
this.router.navigateByUrl('/')
} else {
return true;
}
}