[英]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.