2017-04-15 3 views
0

私がログインしているかどうかを確認するAuthGuardを角度2で使用しているとします。私がログインしていない場合、私は/ loginにリダイレクトされます。リダイレクトロジックはAuthGuardにあります。AngularでのルーティングでcanNotActivateを置き換える良い方法はありますか?

path: '', 
component: HomeComponent, 
canActivate: [AuthGuard] 

しかし、すでにログインしていて、/ログインページに移動しようとするとどうなりますか?ユーザーがすでにログインしていて、ログインページにアクセスしようとすると、ホームページにリダイレクトする最良の方法はありますか?ルータにはcanNotActivateはありません。私は2つのAuthGuardsを作るべきですか? AuthGuardNegateまたは何かと呼ばれるもの?

これには良いアプローチがありますか?

答えて

1

私のやり方は、認証が必要なページにAuthGuardを使用し、ログインしていないときにのみ表示するUnauthGuardを使用することです。あなたが言ったように。 は最善の方法ではないかもしれないが、それはうまく動作します:

import {Injectable} from '@angular/core'; 
import {CanActivate, Router} from '@angular/router'; 
import {AuthService} from '../services/auth.service'; 

@Injectable() 
export class UnauthGuard implements CanActivate { 

    constructor(private router: Router, private authService: AuthService) {} 

    canActivate() { 
     if (this.authService.isLoggedIn()) { 
      this.router.navigate(['/app']); //Path to your authenticated-only page 
     } 
     return true; 
    } 
} 

とあなたのルーティングモジュールで:

{ 
    path: 'login', 
    component: LoginPage, 
    canActivate: [ 
     UnauthGuard 
    ] 
}, 
関連する問題