Bài này hoàn thiện ứng dụng nhiều trang bằng Angular Router và kết nối máy chủ bằng HttpClient: khai báo routes, liên kết, tham số, tải lười và gọi API REST.
Bạn sẽ học được
- Khai báo routes và RouterOutlet
- routerLink và tham số
- Lazy loading component
- Gọi API GET, POST bằng HttpClient
Router
// app.routes.ts
export const routes: Routes = [
{ path: "", component: TrangChu },
{ path: "sinh-vien/:ma", loadComponent: () => import("./chi-tiet").then(m => m.ChiTiet) },
{ path: "**", component: KhongThay }
];
<!-- app.html -->
<a routerLink="/" routerLinkActive="active">Trang chủ</a>
<router-outlet />
// chi-tiet.ts: đọc tham số
ma = inject(ActivatedRoute).snapshot.paramMap.get("ma");HttpClient
// app.config.ts
providers: [provideRouter(routes), provideHttpClient()]
// nguoi-dung.service.ts
@Injectable({ providedIn: "root" })
export class NguoiDungService {
private http = inject(HttpClient);
private url = "https://jsonplaceholder.typicode.com/users";
layDS() { return this.http.get<any[]>(this.url); }
them(u: any) { return this.http.post(this.url, u); }
}
// component
ds = toSignal(inject(NguoiDungService).layDS(), { initialValue: [] });HttpClient trả về Observable (thư viện RxJS); toSignal chuyển thành signal để dùng trong template.
Lưu ý
Khi gọi API từ tên miền khác, máy chủ phải cho phép CORS; khi phát triển có thể dùng proxy của Angular CLI.
Thực hành
- Tạo 3 trang và menu điều hướng.
- Hiển thị danh sách người dùng từ API.
- Trang chi tiết đọc tham số :ma.
Tóm tắt bài học
- Routes + router-outlet tạo nhiều trang.
- loadComponent tải lười.
- HttpClient gọi API, toSignal đưa vào template.

