Protecting Routes with Guards
There are several cases to validate, block user, invalid parameter etc…
Guards support those routing validator
Guards Type
CanActivate | Guard navigation to a route |
CanDeactivate | Guard navigation from a route |
Resolve | Pre-fetch data before activating a route |
CanLoad | Prevent asynchronous routing |
Guard sample
Create guard from CLI
ng g g guard/product-detail
When running this command, we need to select above 4 types(CanActivate, CanActivateChild, CanLoad)
guard/product-detail.guard.ts is generated
Guard code
Let’s take a look guard code.
In this time, the sample is very simple. validate path parameter and if path parameter is invalid, navigate to another page.
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-product', templateUrl: './product.component.html', styleUrls: ['./product.component.scss'] }) export class ProductComponent implements OnInit { pageTitle = ''; constructor(private route: ActivatedRoute) { console.log(this.route.snapshot.paramMap.get('id')); let id = +this.route.snapshot.paramMap.get('id'); // + <- parameter to string this.pageTitle += `:${id}` } ngOnInit(): void { } }
How to use this?
It’s just to register with Route
app-routing.module.t
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { WelcomeComponent } from './welcome/welcome.component'; import { ProductlistComponent } from './productlist/productlist.component'; import { ProductComponent } from './product/product.component'; import { ProductDetailGuard } from './guard/product-detail.guard'; const routes: Routes = [ { path: 'products', component: ProductlistComponent }, { path: 'products/:id', canActivate:[ProductDetailGuard], component: ProductComponent }, { path: 'welcome', component: WelcomeComponent } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
See parameter, canActivate:[] is to register guard into target page component
コメント