> 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],