登錄我有這樣的路線:角2重定向用戶是否在
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
和AuthGuard
:
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(private router: Router,
private authService: AuthService) { }
canActivate() {
if (this.authService.isLoggedIn()) {
return true;
}
this.router.navigate(['login']);
return false;
}
}
當用戶訪問該網站時,他被重定向到登錄頁面。當用戶嘗試訪問/dashboard
路由而沒有驗證時也會發生同樣的情況。如果他已登錄,如何將用戶重定向到/dashboard
?例如,當我訪問myapp.com
並且我已登錄時,我想將其重定向到myapp.com/dashboard
。
上'canActivate'將無法正常工作這樣做呢? 'if(this.authService.isLoggedIn()){this.router.navigate(['dashboard']);返回true; }'。 – developer033
@ developer033,我試過了,它不起作用!會有一個無限循環。 –
嗯,所以你只能在你的'LoginComponent'(在'ngOnInit')上檢查它.. – developer033