LoginSignup
50
38

More than 3 years have passed since last update.

AngularでGuardの導入

Last updated at Posted at 2018-06-06

Guardについて

Routerでページ遷移前にログインされたユーザーなのかのチェックを行いたい時になどに使います。

生成コマンド

AuthGuardという名前で生成します。

$ ng g guard guard/auth

src/app/guard/auth.guard.ts が生成されます。
いつも通り、app.module.tsのprovidersに追加します。

ログインチェック

認証系処理などが書いてあるAuthServiceがあるとします。
そこにログインしているかどうかのチェックする処理を書きます。
今回はトークンベースの認証の場合として、LocalStorageにあるトークンがあるかどうかでチェックします。
(本当はトークンの有効期限があるかのチェックも必要かも)

@Injectable()
export class AuthService {
  .
  .
  .

  isAuthenticated(): boolean {
    const token = localStorage.getItem('token');
    return token != null;
  }
}

AuthGuardの処理

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

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private authService: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    if (!this.authService.isAuthenticated()) {
      this.router.navigate(['login']);
      return false;
    }
    return true;
  }
}

Routeの設定ファイルに処理を挟みたいパスに対してAuthGuardを追加します。

import { AuthGuard } from './guard/auth.guard';

const routes: Routes = [
  { path: '', component: HomeComponent, canActivate: [AuthGuard] },
  { path: 'login', component: LoginComponent }
];

これで完成です。

50
38
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
38