简体   繁体   English

如果用户登录,Angular 2 重定向

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

相关问题 如果用户已登录,则角度重定向到仪表板 - Angular redirect to dashboard if user is logged in 如果已记录用户,则角度登录组件重定向 - Angular Login Component Redirect if User is Already logged 如果用户未登录Angular2 2.0.0-rc.4,则重定向到登录路由 - Redirect to login route if the user not logged in Angular2 2.0.0-rc.4 如果用户未登录,如何重定向到 Angular 自定义登录页面 - How to redirect to an Angular custom made Login page if the user is not logged in Angular 2路由器-注销后,用户尝试导航到登录页面时,我需要app.ts进行重定向 - Angular 2 router - When logged out and a user tries to navigate to a logged in page I need the app.ts to redirect 用户登录 Angular 时如何重定向到不同的主页? - How do I redirect to different home page when user is logged in Angular? AspNetBoilerplate(免费版+ .NET Core + Angular):如果用户已经登录,则从登录页面重定向到首页 - AspNetBoilerplate (Free version + .NET Core + Angular): redirect to home from login page if user is already logged in Angular,如何告诉用户他们已登录或未登录? - Angular, how to tell user they are logged in or not in? Angular 显示登录用户详细信息 - Angular Display Logged In User Details 如果用户已登录,则角度6更改组件 - Angular 6 change component if user is logged in
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM