Skip to main content

Posts

Recent posts

Sharing Data with Subjects & BehaviorSubjects (RxJS) In angular

🚀 What are Subjects & BehaviorSubjects? Subjects are special types of observables in RxJS that allow values to be multicasted to multiple observers. BehaviorSubjects are a type of Subject that also holds the current value and emits it to new subscribers. 📦 Why Use Subjects & BehaviorSubjects? Benefit Description Multicasting Allows multiple subscribers to receive the same values. State Management BehaviorSubjects hold the current value, useful for state management. Flexibility Subjects can be used for various patterns like event handling, data sharing, etc. 🔥 Basic Example Suppose you want to share data between components using a BehaviorSubject: 1. Create a Service with a BehaviorSubject ng generate service data This generates data.service.ts : import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs...

Dependency Injection in Angular

🚀 What is Dependency Injection? Dependency Injection (DI) is a design pattern . It allows a class to receive its dependencies (services, objects) from the outside , rather than creating them itself. Angular has a powerful built-in DI system that manages and injects dependencies automatically. 📦 Why Use Dependency Injection? Benefit Description Loose Coupling Classes are not tightly tied to their dependencies. Reusability Easier to reuse code and services. Testability Easier to mock dependencies for unit testing. Maintainability Cleaner, more modular code. 🔥 Basic Example Suppose you have a service that provides user data: 1. Create a Service ng generate service user This generates user.service.ts : import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' // Angular will automati...

Creating and using services in Angular

🚀 What are Services? Services are classes that provide reusable functionality across your Angular application. They help encapsulate business logic and data access in a centralized way. 📁 1. Create a Service Suppose you want to create a DataService to manage data operations. Generate the service: ng generate service data Inside data.service.ts : import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { private data: any[] = []; constructor() { } getData() { return this.data; } addData(item: any) { this.data.push(item); } } 📄 2. Inject and Use the Service in a Component In app.component.ts : import { Component, OnInit } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppC...

Route guards in Angular

🚀 What are Route Guards? Route Guards are interfaces that allow you to control access to routes in your Angular application. They help protect routes by checking conditions before navigating to them. 📁 1. Create an AuthGuard Suppose you want to create an AuthGuard to protect certain routes. Generate the guard: ng generate guard auth Inside auth.guard.ts : import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService } from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const isLoggedIn = this.authService.isLoggedIn(); if (!isLoggedIn) { this.router.navigate(['/login']); } ...

Lazy Loading in Angular

🚀 What is Lazy Loading? Lazy Loading means loading modules only when needed , not when the app starts. It helps improve the initial load time of your Angular app. 📁 1. Create a Feature Module Suppose you want to lazy-load a ProductsModule . Generate a module and a component: ng generate module products --route products --module app.module ng generate component products/products-list or manually: ng generate module products ng generate component products/products-list Inside products-routing.module.ts : import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ProductsListComponent } from './products-list/products-list.component'; const routes: Routes = [ { path: '', component: ProductsListComponent } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class ProductsRoutingModule { } Inside products.module.ts : import { NgModu...

Route Parameters in Angular

How to define a route with a parameter: In your app-routing.module.ts : const routes: Routes = [ { path: 'product/:id', component: ProductComponent } ]; :id is a route parameter (dynamic value). Accessing the Route Parameter in the Component In product.component.ts : import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-product', templateUrl: './product.component.html' }) export class ProductComponent { productId!: string; constructor(private route: ActivatedRoute) {} ngOnInit() { this.productId = this.route.snapshot.paramMap.get('id')!; // OR you can subscribe to changes: this.route.paramMap.subscribe(params => { this.productId = params.get('id')!; }); } } Navigating to a Route with Parameters In your template: <a [routerLink]="['/product', 42]">View Product 42</a> or programmatically: this.router.navigate(['/pr...