Bird
0
0

Consider this Angular service and component:

medium📝 component behavior Q4 of 15
Angular - Services and Dependency Injection
Consider this Angular service and component:
import { Injectable } from '@angular/core';
@Injectable({providedIn: 'root'})
export class MessageService {
  getMessage() { return 'Hello'; }
}
@Component({selector: 'app-sample', template: ''})
export class SampleComponent {
  constructor(private msgService: MessageService) {
    console.log(this.msgService.getMessage());
  }
}

What will be printed in the console when SampleComponent is instantiated?
AError: No provider for MessageService
Bundefined
CHello
Dnull
Step-by-Step Solution
Solution:
  1. Step 1: Service providedIn root

    The service is provided at root level, so Angular creates a singleton instance.
  2. Step 2: Constructor injection

    The component receives the service instance via constructor injection.
  3. Step 3: Method call

    Calling getMessage() returns 'Hello', which is logged.
  4. Final Answer:

    Hello -> Option C
  5. Quick Check:

    Root provided services are injectable everywhere [OK]
Quick Trick: Root provided services are singleton and injectable [OK]
Common Mistakes:
MISTAKES
  • Assuming service is not provided and causes error
  • Expecting undefined because of missing initialization

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Angular Quizzes