[英]angular 2 Auth guard breaks redirect
这是我的app-routing.module.ts
:
const routes: Routes = [
{ path: '', redirectTo: '/app/elements', pathMatch: 'full' },
{path: 'app', component:ElementsComponent, children:[
{ path: 'details/:id', component: ElementDetailComponent, canActivate:[AuthGuard]},
{ path: 'elements', component: ElementListComponent, canActivate:[AuthGuard] },
{ path: 'user/signup', component: SignupComponent },
{ path: 'user/login', component: LoginComponent },
{ path: 'user/logout', component: LogoutComponent }
]}
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ],
providers: [AuthGuard]
})
export class AppRoutingModule {}
如您所见,路径''
我正在重定向到/app/elements
这是我的主页。 在我实现AuthGuard
之前,它一直运行良好,如下所示:
@Injectable()
export class AuthGuard implements CanActivate{
public allowed: boolean;
constructor(private af: AngularFire, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.af.auth.subscribe((auth) => {
if(auth == null) {
this.router.navigate(['/app/user/login']);
this.allowed = false;
} else {
this.allowed = true;
}
});
return this.allowed;
}
}
现在,如果用户未登录并转到http://localhost:4200/
,则重定向有效,并且尝试转到http://localhost:4200/app/elements
,守护程序检测到用户未登录并重定向到登录页面。
问题是用户是否登录并尝试访问http://localhost:4200/
。 在这种情况下,什么也不会发生,用户停留在该URL空白页面。
为什么在这种情况下重定向不起作用? 有办法解决吗?
在canActivate
的前返回firebase
观察到的议决,所以canActivate
将始终返回false,但canActivate
可以返回一个承诺或可观察到的。
应该工作:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.af.auth
.map(auth => auth != null) // null means not authenticated
.do(isAuthenticated => { // change routes if not authenticated
if(!isAuthenticated) {
this.router.navigate(['/app/user/login']);
}
});
}
您可以使用保留身份验证状态的服务。 之后,只需使用没有订阅的代码即可。 因为它异步执行并制动了代码。
public canActivate() {
if (this.authService.isAuthenticated)
return true;
this.router.navigate(['/app/user/login']);
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.