Services help share data and logic across different parts of an Angular app. They keep code organized and avoid repeating the same work in many places.
Why services are needed in Angular
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MyService { // service logic here }
The @Injectable decorator marks the class as a service that can be injected.
Using providedIn: 'root' makes the service available app-wide without extra setup.
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { getData() { return ['apple', 'banana', 'cherry']; } }
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class LoggerService { log(message: string) { console.log('LOG:', message); } }
This example shows a service that stores messages. The component uses the service to add and display messages. This keeps the message logic separate from the UI.
import { Component } from '@angular/core'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class MessageService { private messages: string[] = []; add(message: string) { this.messages.push(message); } getMessages() { return this.messages; } } @Component({ selector: 'app-root', template: ` <h1>Messages</h1> <button (click)="addMessage()">Add Message</button> <ul> <li *ngFor="let msg of messages">{{ msg }}</li> </ul> ` }) export class AppComponent { messages: string[] = []; count = 1; constructor(private messageService: MessageService) { this.messages = this.messageService.getMessages(); } addMessage() { this.messageService.add(`Message ${this.count++}`); this.messages = this.messageService.getMessages(); } }
Services help keep your app clean by separating data and logic from the user interface.
Injecting services makes it easy to reuse code and share information between components.
Always use services for tasks like data fetching, state management, or utility functions.
Services let you share data and logic across your Angular app.
They keep components simple and focused on displaying the UI.
Using services makes your app easier to maintain and test.
Practice
Solution
Step 1: Understand the role of services
Services hold shared data and logic that multiple components can use.Step 2: Compare with components
Components focus on showing the UI, not on sharing data or logic.Final Answer:
To share data and logic across components easily -> Option BQuick Check:
Services share data and logic = A [OK]
- Thinking services slow down the app
- Believing services replace HTML
- Confusing services with components
Solution
Step 1: Recall Angular dependency injection syntax
Angular injects services by declaring them as private/public in the constructor parameters.Step 2: Check each option
constructor(private myService: MyService) {} uses correct syntax with private and type annotation. Others create instances manually or miss type.Final Answer:
constructor(private myService: MyService) {} -> Option DQuick Check:
Use private with type in constructor = D [OK]
- Manually creating service instances
- Missing type annotation
- Assigning service without new keyword
export class CounterService {
count = 0;
increment() { this.count++; }
}
@Component({ selector: 'app-one', template: '' })
export class OneComponent {
constructor(private counter: CounterService) {}
ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}
@Component({ selector: 'app-two', template: '' })
export class TwoComponent {
constructor(private counter: CounterService) {}
ngOnInit() { this.counter.increment(); console.log(this.counter.count); }
}Solution
Step 1: Understand service instance sharing
Angular provides the same service instance to both components if the service is singleton.Step 2: Trace increments and logs
OneComponent increments count to 1 and logs 1. Then TwoComponent increments to 2 and logs 2.Final Answer:
1 and 2 -> Option AQuick Check:
Shared service count increments = C [OK]
- Assuming separate service instances per component
- Ignoring increment effect order
- Thinking count resets each time
@Injectable({ providedIn: 'root' })
export class DataService {
data = [];
}
@Component({ selector: 'app-test', template: '' })
export class TestComponent {
dataService: DataService;
constructor(private dataService: DataService) {
}
}Solution
Step 1: Identify service instantiation method
The component creates a new service instance manually using new, bypassing Angular's injector.Step 2: Understand Angular DI pattern
Services should be injected via constructor parameters to get the singleton instance managed by Angular.Final Answer:
Service should be injected, not created with new -> Option AQuick Check:
Inject services via constructor, not new [OK]
- Creating service instances manually
- Ignoring Angular dependency injection
- Misunderstanding providedIn usage
Solution
Step 1: Identify need for shared state
Login status must be shared and consistent across components.Step 2: Choose best practice
Using a UserService to hold login state and methods keeps components simple and shares data.Final Answer:
Create a UserService with login status and methods, inject it in components -> Option CQuick Check:
Use service to share state and logic [OK]
- Duplicating state in components
- Putting logic in templates
- Avoiding services for shared data
Ready to prove it?
Pass the test and this pattern moves unknown
