[英]How to redirect another component when canActivate returns false?
Hi I am using routing in angular 5 and I have a login path that uses canActivate property 嗨我在angular 5中使用路由,我有一个使用canActivate属性的登录路径
can I redirect to another path when canActivate is false? 当canActivate为false时,我可以重定向到另一个路径吗? I don't want user to see the login page if he/she is logged in. 如果他/她已登录,我不希望用户看到登录页面。
here main service returns false if user is logged in 如果用户已登录,则此主服务返回false
{
path: 'login',
component: RegisterLoginComponent,
canActivate: [MainService]
}
I think a better approach would be to protect your default path with a Guard and redirect to /login
from there if authentication fails. 我认为更好的方法是使用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;
}
Note : If you want to control where you redirect to, you have access to the url that the user was trying to access under route.url
. 注意 :如果要控制重定向到的位置,则可以访问用户尝试在route.url
下访问的route.url
。 You can check its value and then navigate to specific url, instead of always to '/login'. 您可以检查其值,然后导航到特定网址,而不是始终转到“/ login”。
Here's a quick sample code that does this redirection with asynchronous code as well. 这是一个使用异步代码进行重定向的快速示例代码。 https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fauth-with-redirect.guard.ts https://stackblitz.com/edit/angular-async-guard-redirect?file=src%2Fapp%2Fauth-with-redirect.guard.ts
Redirect in login service if credentials match 如果凭据匹配,则在登录服务中重定向
this.authService.signin(user)
.subscribe(
data => {
this.router.navigateByUrl('/dashboard');
},
error => console.error(error)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.