Consider an Angular service that holds a counter value. If two different components inject this service and update the counter, what will be the final counter value seen by both components?
Assume the service starts with counter = 0. Component A increments it by 1, then Component B increments it by 2.
export class CounterService { counter = 0; increment(value: number) { this.counter += value; } } // Component A calls: counterService.increment(1); // Component B calls: counterService.increment(2);
Think about how Angular injects services by default and whether the service instance is shared.
Angular services provided in root are singletons. Both components share the same instance, so increments accumulate.
Which of the following is the correct syntax to inject a service named DataService into a standalone Angular component using the new Angular 17+ inject() function?
Standalone components can use the inject() function instead of constructor injection.
The inject() function is the new recommended way to get services in standalone components without constructors.
Given this Angular service and component code, what will be logged to the console?
export class MessageService {
message = 'Hello';
updateMessage(newMsg: string) {
setTimeout(() => {
this.message = newMsg;
}, 1000);
}
}
@Component({
standalone: true,
selector: 'app-msg',
template: `{{msgService.message}}`
})
export class MsgComponent {
constructor(public msgService: MessageService) {}
ngOnInit() {
this.msgService.updateMessage('Hi');
console.log(this.msgService.message);
}
}
Consider when the setTimeout callback runs compared to the console.log.
The console.log runs before the timeout changes the message, so it logs the old value. The template updates after the message changes.
An Angular service holds user data but resets to initial state when navigating between routes. What is the most likely cause?
Think about how Angular creates service instances with lazy-loaded modules.
Services provided in lazy-loaded modules create new instances per module load, causing state reset on navigation.
Why do Angular developers often use services to manage shared state instead of component inputs or outputs?
Consider how shared state should behave across multiple components.
Services act as a centralized place to hold and manage state, making it easier to share and persist data across components.