LoginSignup
0
0

More than 1 year has passed since last update.

angularのroutingに挟むguard

Last updated at Posted at 2022-07-08
> ng generate guard guard-name

が使える

生成された後はこんな感じで書いて

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree,  Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MyAuthGuard implements CanActivate {
  constructor(private router: Router) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    // return false;
    return this.router.parseUrl('/auth?url='+state.url);
  }
  
}

こんな感じで書けばOK
app.routing.ts


export const routes: Routes = [
  {
    path: 'pages',
    component: Pages,
    canActivate: [MyAuthGuard],
0
0
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
0
0