我已为我的应用添加了登录功能。当有人使用空白路径(http://example.com)导航到URL时,我希望HomeComponent显示将激活AuthGuard,但保持URL路径为空。我还在本地测试,这可能是问题所在?我不确定。
现在发生了什么 - 当我导航到localhost:3000 /我什么都没得到,只是一个空白屏幕。当我导航到localhost:3000 / home时,我让我的HomeComponent显示没有问题,但我希望在URL为localhost时调用HomeComponent:3000 /。
这是我的app.module文件 - 我不确定我需要发布哪些其他文件,因为问题在于路由。就像我说的,我可以通过键入路径来获取所有其他组件。但对于Home,我不想输入路径。
app.module.ts
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', component: HomeComponent, pathMatch: 'full', canActivate: [AuthGuard] },
我也试过像这样设置我的默认路线,但仍然是同样的问题:
<base href="/" />
我的基础href设置为:
String newLine = System.getProperty("line.separator");
String pessoapopu = driver.findElement(By.className("artdeco-toast-message"))
.getText().replaceAll(newLine, "");
我没有收到任何错误,我的控制台看起来很干净。再次,如果我将“/ home”添加到我的URL末尾,我可以正常导航,但我想要一个空白的URL路径来显示带有AuthGuard的HomeComponent。
我一直在阅读文档和其他问题,但没有任何对我有用。我不确定我错过了什么。任何帮助将不胜感激。如果我需要发布任何其他代码段,请告诉我。提前谢谢。
答案 0 :(得分:0)
与许多其他框架一样,Angular 2中的路由依赖于路由的顺序。
path: ''
的第一条路线与每个请求相匹配,并将被执行。但如果您的用户未获得授权,则警卫会阻止该请求。
建议将路线从更具体的路线分类到不太具体的路线,如下所示:
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: '**', redirectTo: '/' }
使用此配置,将从最后一个路由捕获对localhost:3000 /的请求,并重定向到/home
。
使用路由'**'
,您将捕获路由配置中未涵盖的每个请求,并将其重定向到/
,然后重定向到主页。
我不知道这是否重要,但您的基数设置为<base href='/' />
。 Angular的文档说它必须是<base href='/'>
。
答案 1 :(得分:0)
在我的情况下,此代码行之有效。
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
const isLoggedIn = this.authService.isLoggedIn();
if (!isLoggedIn) {
const bool = confirm('Dany access!\nCan i redirect u to login page?');
return await (bool) ? this.router.navigateByUrl('/login') : this.router.navigateByUrl('/') ;
}
return isLoggedIn;
}
}
我在Ionic项目中看到了这段代码,直到现在我再也没有重定向问题了。
答案 2 :(得分:-1)
如果你看Configuration section of the routing docs
您可以在第二次尝试时看到错过了/
。您还应该从空路线中删除AuthGuard
。
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
您可能还需要更新AuthGuard
以包含this answer中描述的内容,如下所示
@Injectable()
export class AuthGuard implements CanActivate {
auth: any = {};
constructor(private authService: AuthService, private router: Router) {
}
canActivate() {
if (/*user is logged in*/) {
return true;
}
else {
this.router.navigate(['/login']);
}
return false;
}
}