Single-Page Application එකක වුවද, පරිශීලකයාට විවිධ පිටු අතර සැරිසරන (navigate) අත්දැකීමක් ලබා දෙන්නේ කෙසේදැයි Angular Router භාවිතයෙන් ඉගෙන ගනිමු.
Angular CLI භාවිතයෙන් නව project එකක් සාදන විට, "Would you like to add Angular routing?" ලෙස අසන ප්රශ්නයට yes (y) ලෙස පිළිතුරු දීමෙන් routing ස්වයංක්රීයව සකස් වේ. මෙයින් `app-routing.module.ts` නමින් ගොනුවක් නිර්මාණය වේ.
ඔබ එසේ නොකළේ නම්, app.module.ts ගොනුවට `RouterModule` import කර එය જાતેම සකස් කළ හැක.
<router-outlet></router-outlet> යොදයි.routerLink directive එක භාවිතා කරමින් සබැඳි නිර්මාණය කරයි. මෙය පිටුව refresh වීම වළක්වයි.`app-routing.module.ts` ගොනුවේ `routes` array එක තුළ route objects ලෙස path සහ component යුගල නිර්වචනය කරයි.
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
const routes: Routes = [
{ path: '', component: HomeComponent }, // Default route
{ path: 'about', component: AboutComponent },
{ path: 'contact', component: ContactComponent }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
ඉන්පසු `app.component.html` හි navigation links සහ `router-outlet` යොදන ආකාරය:
<!-- app.component.html -->
<nav>
<a routerLink="/">Home</a> |
<a routerLink="/about">About Us</a> |
<a routerLink="/contact">Contact</a>
</nav>
<h1>My Awesome App</h1>
<!-- Routed components will be displayed here -->
<router-outlet></router-outlet>
බොහෝ විට URL එක හරහා ගතික (dynamic) දත්ත යැවීමට අවශ්ය වේ. උදාහරණයක් ලෙස, නිශ්චිත පරිශීලකයෙකුගේ (`user`) තොරතුරු බැලීමට `users/1` හෝ `users/2` වැනි path එකක් භාවිතා කළ හැක.
මෙය සිදු කිරීමට, route path එකේ `:id` වැනි placeholder එකක් යොදයි.
// In app-routing.module.ts
{ path: 'users/:id', component: UserDetailsComponent }
Component එක තුළ මෙම `id` එක ලබාගැනීමට `ActivatedRoute` service එක භාවිතා කරයි.
// user-details.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({ ... })
export class UserDetailsComponent implements OnInit {
userId: string;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.userId = this.route.snapshot.paramMap.get('id');
// Now you can use this.userId to fetch user data
}
}
Route Guards යනු යම් route එකකට ඇතුළු වීමට (activate) හෝ ඉන් පිටවීමට (deactivate) පෙර යම් කොන්දේසියක් පරීක්ෂා කිරීමට ඉඩ සලසන services වේ.
Lazy Loading යනු යෙදුම ආරම්භයේදීම සියලුම modules load නොකර, පරිශීලකයා යම් route එකකට පිවිසෙන විට පමණක් ඊට අදාළ module එක load කිරීමයි. මෙය විශාල යෙදුම්වල ආරම්භක loading කාලය (initial load time) අඩු කිරීමට බෙහෙවින් උපකාරී වේ.
// In app-routing.module.ts
const routes: Routes = [
// ... other routes
{
path: 'admin',
loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule)
}
];