[英]How to redirect another component when canActivate returns false?
嗨我在angular 5中使用路由,我有一個使用canActivate屬性的登錄路徑
當canActivate為false時,我可以重定向到另一個路徑嗎? 如果他/她已登錄,我不希望用戶看到登錄頁面。
如果用戶已登錄,則此主服務返回false
{
path: 'login',
component: RegisterLoginComponent,
canActivate: [MainService]
}
我認為更好的方法是使用Guard保護您的默認路徑,並在身份驗證失敗時從那里重定向到/login
。
/* AuthService */
isLoggedIn(): boolean {
// check if user is logged in
return isUserLoggedIn;
}
/* AuthGuard */
import { Router } from '@angular/router';
import { AuthService } from './auth.service';
...
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
// check if user is logged in
const loggedIn: boolean = this.authService.isLoggedIn();
// if not, redirect to /login
if (!loggedIn) {
this.router.navigate(['/login']);
}
return loggedIn;
}
注意 :如果要控制重定向到的位置,則可以訪問用戶嘗試在route.url
下訪問的route.url
。 您可以檢查其值,然后導航到特定網址,而不是始終轉到“/ login”。
這是一個使用異步代碼進行重定向的快速示例代碼。 https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fauth-with-redirect.guard.ts
如果憑據匹配,則在登錄服務中重定向
this.authService.signin(user)
.subscribe(
data => {
this.router.navigateByUrl('/dashboard');
},
error => console.error(error)
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.