[英]Angular 2 redirect if user is logged in
I have routes like this:我有这样的路线:
const routes: Routes = [
{ path: '', redirectTo: '/login', pathMatch: 'full' },
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
and 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;
}
}
When the user visits the website, he gets redirected to the login page.当用户访问该网站时,他会被重定向到登录页面。 Same happens when the user tries to access /dashboard
route without authentication.当用户尝试在没有身份验证的情况下访问/dashboard
路由时,也会发生同样的情况。 How can I redirect the user to /dashboard
if he's logged in?如果用户已登录,我如何将用户重定向到/dashboard
? For example, when I visit myapp.com
and I'm logged in I want to be redirected to myapp.com/dashboard
.例如,当我访问myapp.com
并登录时,我想被重定向到myapp.com/dashboard
。
You want to look at the resolve
property within the [ Route
interface].您想查看 [ Route
interface] 中的resolve
属性。
All of the following properties are available to a route:以下所有属性均可用于路由:
export interface Route {
path?: string;
pathMatch?: string;
matcher?: UrlMatcher;
component?: Type<any>;
redirectTo?: string;
outlet?: string;
canActivate?: any[];
canActivateChild?: any[];
canDeactivate?: any[];
canLoad?: any[];
data?: Data;
resolve?: ResolveData;
children?: Routes;
loadChildren?: LoadChildren;
runGuardsAndResolvers?: RunGuardsAndResolvers;
_loadedConfig?: LoadedRouterConfig;
}
resolve
is designed to allow you to load some type of data before proceeding to the route. resolve
旨在允许您在继续路由之前加载某种类型的数据。 The signature for resolve
looks like this: resolve
的签名如下所示:
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) : Observable<T>|Promise<T>|T
We can ignore that signature, however, and override it because, in this case, we want to redirect to /dashboard if the user is logged in .但是,我们可以忽略该签名并覆盖它,因为在这种情况下,我们希望在用户登录时重定向到/dashboard 。 Otherwise, display /login route normally.否则,正常显示/login路由。
The solution is to create an injectable
class and attach it to the login route's resolve
property.解决方案是创建一个injectable
类并将其附加到登录路由的resolve
属性。
@Injectable()
export class IsLoggedIn {
constructor(
private router: Router,
private authService: AuthService) {
}
resolve(): void {
if (this.authService.isAuthenticated) this.router.navigate(['/dashboard'])
}
}
On your /login route, add the resolve property.在您的/login路由上,添加 resolve 属性。
{
path: 'login',
component: LoginComponent,
resolve: [IsLoggedIn]
}
Import the class in AppModule
and add it to providers
.在AppModule
导入类并将其添加到providers
。
providers: [
IsLoggedIn
]
Now anytime a logged in user attempts to go to /login , they'll be redirected to /dashboard without seeing the login page.现在,无论何时登录用户尝试转到/login ,他们都将被重定向到/dashboard而不会看到登录页面。
In this case I would probably redirect everything to DashboardComponent
using在这种情况下,我可能会将所有内容重定向到DashboardComponent
使用
{path: '', redirectTo: 'dashboard', pathMatch: 'full'}
and than the dashboard component can determinate if the user is logged in or not (as it has AuthGuard active), and if the user is not logged in it would redirect him to login.并且仪表板组件可以确定用户是否已登录(因为 AuthGuard 处于活动状态),如果用户未登录,它会将他重定向到登录。
Probably the quickest thing to do is to tweak your LoginComponent
.可能最快的方法是调整您的LoginComponent
。
Given that this.authService.isLoggedIn()
returns a boolean.鉴于this.authService.isLoggedIn()
返回一个布尔值。 In your LoginComponent
you can quickly check the state in ngOnInit
as below:在您的LoginComponent
您可以快速检查ngOnInit
的状态,如下所示:
import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import {AuthService} from '<path_to_your_auth_service>';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss'],
providers: []
})
export class LoginComponent implements OnInit {
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _authService: AuthService
)
ngOnInit() {
// get return url from route parameters or default to '/'
this.returnUrl = this._route.snapshot.queryParams['returnUrl'] || '/';
// CHECK THE isLoggedIn STATE HERE
if (this._authService.isLoggedIn()) {
this._router.navigate([this.returnUrl]);
}
}
// Rest fo the logic here like login etc
login() { }
}
Note that you're only adding this to ngOnInit
请注意,您只是将此添加到ngOnInit
if (this._authService.isLoggedIn()) {
this._router.navigate([this.returnUrl]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.