Course Progress 76%

Angular Services

Angular Services application का backbone होते हैं। Services का main purpose business logic, data handling और reusable functionality को components से अलग रखना होता है। Proper service design से Angular application scalable, testable और maintainable बनती है।

इस chapter में हम Angular Services को beginner से advanced level तक detail में समझेंगे, exactly उसी depth में जैसा official documentation expect करती है, लेकिन language simple और practical रहेगी।

Angular Service क्या होता है

Angular Service एक normal TypeScript class होती है जो Angular के Dependency Injection system के through components, directives या other services में inject की जाती है।

Service का use होता है:

  • Business logic रखने के लिए
  • API calls handle करने के लिए
  • Shared data manage करने के लिए
  • Utility functions provide करने के लिए

Service का UI से direct relation नहीं होता।

Service क्यों जरूरी है

अगर सारा logic component में ही लिखा जाए तो:

  • Components बहुत heavy हो जाते हैं
  • Code duplication बढ़ता है
  • Testing मुश्किल हो जाती है
  • Maintainability खराब होती है

Service इन problems को solve करती है।

Basic Service Creation

Angular CLI से service generate करना best practice है।

ng generate service user

यह command create करती है:

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() {}

}

@Injectable() decorator Angular को बताता है कि यह class DI system में use होगी।

providedIn: ‘root’ का मतलब

providedIn: 'root' का मतलब है:

  • Service application-wide singleton होगी
  • Service root injector में register होगी
  • Extra configuration की जरूरत नहीं

यह modern Angular में recommended approach है।

Service का Simple Use Case

मान लेते हैं हमें user data fetch करना है।

export class UserService {

  getUsers() {
    return ['Amit', 'Ravi', 'Neha'];
  }

}

Component में inject करना:

export class AppComponent {

  users: string[] = [];

  constructor(private userService: UserService) {
    this.users = this.userService.getUsers();
  }

}

Component सिर्फ data consume कर रहा है, logic service में है।

Dependency Injection का Basic Concept

Angular में services manually create नहीं की जातीं।

गलत तरीका:

const service = new UserService();

सही तरीका:

constructor(private userService: UserService) {}

Angular खुद service का instance manage करता है।

Service और Component का Relation

Component:

  • UI handle करता है
  • User interaction manage करता है

Service:

  • Data process करती है
  • Logic execute करती है
  • Reusable behavior provide करती है

यह separation Angular architecture का core principle है।

Multiple Components में Service Sharing

Same service multiple components में inject की जा सकती है।

constructor(private userService: UserService) {}

जब service root level पर provided होती है, तो सभी components same instance share करते हैं।

यह shared state scenarios में बहुत useful है।

Service में HTTP Logic

Real-world services mostly API calls handle करती हैं।

@Injectable({ providedIn: 'root' })
export class ProductService {

  constructor(private http: HttpClient) {}

  getProducts() {
    return this.http.get('/api/products');
  }

}

Component:

this.productService.getProducts().subscribe(data => {
  this.products = data;
});

Service API abstraction provide करती है।

Service में State Management (Basic)

Service state भी hold कर सकती है।

export class CounterService {
  count = 0;

  increment() {
    this.count++;
  }
}

Multiple components same counter value access कर सकते हैं।

यह lightweight state management का simplest form है।

Service Lifecycle

Service lifecycle injector पर depend करता है।

  • Root provided service app lifecycle तक alive रहती है
  • Component-level provided service component destroy होने पर destroy हो जाती है

Service खुद lifecycle hooks provide नहीं करती, लेकिन injector lifecycle follow करती है।

Service को Component-Level Provide करना

@Component({
  selector: 'app-test',
  providers: [TestService]
})
export class TestComponent {}

इस case में:

  • हर component instance को new service instance मिलेगा
  • State isolated रहेगी

यह approach scoped services के लिए useful है।

Service में RxJS का Use

Services RxJS के लिए ideal place हैं।

private data$ = new BehaviorSubject<number>(0);

getData() {
  return this.data$.asObservable();
}

updateData(value: number) {
  this.data$.next(value);
}

Components सिर्फ subscribe करते हैं।

Service और Signals (Intro Level)

Modern Angular में services signals भी expose कर सकती हैं।

count = signal(0);

increment() {
  this.count.update(v => v + 1);
}

Components direct reactive state consume कर सकते हैं।

Common Service Design Patterns

Angular में commonly used patterns:

  • Facade Service
  • Data Service
  • Utility Service
  • State Service

हर service का single clear responsibility होनी चाहिए।

Service Naming Conventions

Best practices:

  • Suffix हमेशा Service रखें
  • Meaningful नाम रखें
  • Generic नाम avoid करें

Examples:

  • UserService
  • AuthService
  • ProductApiService

Common Mistakes

  • Service में UI logic डालना
  • Component में heavy business logic रखना
  • Services को manually instantiate करना
  • God-service बनाना (बहुत ज्यादा responsibility)

Service कब Use करें

Angular Service use करें जब:

  • Logic multiple components में shared हो
  • External API interaction हो
  • Application state manage करनी हो
  • Reusable utilities चाहिए हों

Angular Services Angular architecture की foundation हैं। Strong service design के बिना large Angular application maintain करना almost impossible हो जाता है। अगले chapter में हम Dependency Injection को deep में समझेंगे, जहाँ providers, injectors और advanced DI patterns cover होंगे।