Bird
Raised Fist0
Angularframework~20 mins

How dependency injection works in Angular - Practice Exercises

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Angular Dependency Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
What is the role of the injector in Angular's dependency injection?

In Angular, the injector is a core part of dependency injection. What does it do?

AIt creates and provides instances of services when requested by components or other services.
BIt compiles Angular templates into JavaScript code.
CIt manages routing between different pages in the application.
DIt handles user input events like clicks and key presses.
Attempts:
2 left
💡 Hint

Think about who is responsible for giving components the services they need.

❓ component_behavior
intermediate
2:00remaining
What happens if a service is provided in a component's providers array?

Consider a service provided in the providers array of a component. How does Angular handle this service instance?

AAngular uses the same global instance of the service for the entire app.
BAngular creates a new instance of the service only for that component and its children.
CAngular throws an error because services cannot be provided in components.
DAngular creates a new instance of the service for every component in the app.
Attempts:
2 left
💡 Hint

Think about service scope and how providing in a component affects instance sharing.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly injects a service using Angular's constructor injection?

Choose the correct way to inject a service named DataService into a component using Angular's constructor injection.

Angular
import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-example',
  template: '<p>Example works!</p>'
})
export class ExampleComponent {
  constructor( /* injection here */ ) {}
}
Aconstructor(@Inject(DataService) private dataService: DataService) {}
Bconstructor(dataService: DataService) { this.dataService = dataService; }
Cconstructor(private dataService) {}
Dconstructor(private dataService: DataService) {}
Attempts:
2 left
💡 Hint

Remember how TypeScript and Angular use constructor parameters with access modifiers for injection.

❓ lifecycle
advanced
2:00remaining
When is a service instance created by Angular's injector?

At what point does Angular create an instance of a service provided in the root injector?

AWhen the first component or service requests it (lazy creation).
BImmediately when the app starts, before any component loads.
COnly when the service is manually instantiated in code.
DWhen the Angular compiler processes the service file.
Attempts:
2 left
💡 Hint

Think about when Angular actually needs the service instance.

🔧 Debug
expert
3:00remaining
Why does this Angular component fail to inject the service?

Given this component code, why does Angular throw an error about MyService not being provided?

Angular
import { Component } from '@angular/core';
import { MyService } from './my.service';

@Component({
  selector: 'app-test',
  template: '<p>Test works!</p>'
})
export class TestComponent {
  constructor(private myService: MyService) {}
}
AThe component selector is missing from the module declarations.
BThe constructor parameter is missing the <code>public</code> access modifier.
CThe service <code>MyService</code> is not listed in any <code>providers</code> array or marked with <code>@Injectable({providedIn: 'root'})</code>.
DThe service file path is incorrect in the import statement.
Attempts:
2 left
💡 Hint

Check how Angular knows where to get the service instance from.

Practice

(1/5)
1. What is the main purpose of dependency injection in Angular?
easy
A. To write all code inside a single file
B. To manually create instances of services inside components
C. To provide components with the services they need automatically
D. To prevent components from using any services

Solution

  1. Step 1: Understand dependency injection concept

    Dependency injection automatically provides required services to components without manual creation.
  2. Step 2: Compare options with this concept

    Only To provide components with the services they need automatically describes automatic provision of services, which is the core of dependency injection.
  3. Final Answer:

    To provide components with the services they need automatically -> Option C
  4. Quick Check:

    Dependency injection = automatic service provision [OK]
Hint: Dependency injection means Angular gives services automatically [OK]
Common Mistakes:
  • Thinking you must create service instances manually
  • Believing dependency injection restricts service use
  • Confusing dependency injection with code organization
2. Which decorator makes a class injectable in Angular?
easy
A. @Component
B. @Input
C. @NgModule
D. @Injectable

Solution

  1. Step 1: Identify Angular decorators for injection

    The decorator @Injectable marks a class as available for dependency injection.
  2. Step 2: Eliminate other decorators

    @Component is for components, @NgModule for modules, and @Input for input properties, none make a class injectable.
  3. Final Answer:

    @Injectable -> Option D
  4. Quick Check:

    @Injectable = makes class injectable [OK]
Hint: Use @Injectable to mark services for injection [OK]
Common Mistakes:
  • Confusing @Component with @Injectable
  • Using @NgModule to make services injectable
  • Forgetting to add @Injectable to services
3. Given this Angular service and component code, what will be logged?
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log(message: string) {
    console.log('Log:', message);
  }
}

import { Component } from '@angular/core';
import { LoggerService } from './logger.service';

@Component({ selector: 'app-root', template: '' })
export class AppComponent {
  constructor(private logger: LoggerService) {
    this.logger.log('Hello');
  }
}
medium
A. Log: Hello
B. Error: LoggerService not found
C. No output
D. Log: undefined

Solution

  1. Step 1: Understand service injection in constructor

    The LoggerService is injected into AppComponent via constructor and used to log a message.
  2. Step 2: Analyze the log call

    The log method prints 'Log:' plus the message 'Hello', so console shows 'Log: Hello'.
  3. Final Answer:

    Log: Hello -> Option A
  4. Quick Check:

    Injected service logs message correctly [OK]
Hint: Injected services work via constructor parameters [OK]
Common Mistakes:
  • Expecting error if service is providedIn root
  • Thinking log method won't run without template
  • Confusing console output with return value
4. What is wrong with this Angular service injection code?
import { Injectable } from '@angular/core';

@Injectable()
export class DataService {
  getData() { return [1, 2, 3]; }
}

import { Component } from '@angular/core';

@Component({ selector: 'app-data', template: '' })
export class DataComponent {
  constructor(private dataService: DataService) {}
}
medium
A. DataComponent constructor should not have parameters
B. DataService is not provided in any injector
C. DataService class is missing @Component decorator
D. getData method must be static

Solution

  1. Step 1: Check service provider configuration

    The service has @Injectable() but no providedIn or provider registration, so Angular doesn't know where to provide it.
  2. Step 2: Understand injection failure cause

    Without being provided, Angular throws an error when injecting DataService into DataComponent.
  3. Final Answer:

    DataService is not provided in any injector -> Option B
  4. Quick Check:

    Missing provider causes injection error [OK]
Hint: Always provide services via providedIn or providers array [OK]
Common Mistakes:
  • Assuming @Injectable alone provides the service
  • Adding @Component to services incorrectly
  • Thinking constructor parameters are optional for injection
5. You want to inject two different services of the same class but with different configurations in Angular. Which approach correctly achieves this?
hard
A. Use Angular injection tokens to provide different configurations and inject by token
B. Create two different classes extending the service and inject each separately
C. Use @Injectable({ providedIn: 'root' }) on the class and inject twice in constructor
D. Inject the service once and manually change its configuration before each use

Solution

  1. Step 1: Understand multiple instances need

    Injecting the same class twice with different configs requires distinguishing them in Angular's injector.
  2. Step 2: Use injection tokens for different configs

    Angular injection tokens allow providing multiple versions of the same class with different configurations and injecting them separately.
  3. Step 3: Evaluate other options

    Use @Injectable({ providedIn: 'root' }) on the class and inject twice in constructor injects the same instance twice, B duplicates classes unnecessarily, D is error-prone and not recommended.
  4. Final Answer:

    Use Angular injection tokens to provide different configurations and inject by token -> Option A
  5. Quick Check:

    Injection tokens enable multiple configured instances [OK]
Hint: Use injection tokens for multiple differently configured services [OK]
Common Mistakes:
  • Injecting same service twice without tokens
  • Creating duplicate service classes unnecessarily
  • Changing service config manually at runtime
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard