Bird
Raised Fist0
Angularframework~20 mins

Service-to-service injection in Angular - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Service Injection Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output of this Angular service injection?

Given two Angular services where ServiceB injects ServiceA, what will be logged when ServiceB.logMessage() is called?

Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ServiceA {
  message = 'Hello from ServiceA';
}

@Injectable({ providedIn: 'root' })
export class ServiceB {
  constructor(private serviceA: ServiceA) {}

  logMessage() {
    console.log(this.serviceA.message);
  }
}

// Assume ServiceB.logMessage() is called in a component
ALogs: 'undefined'
BLogs: 'Hello from ServiceA'
CThrows a runtime error: Cannot read property 'message' of undefined
DLogs: 'Hello from ServiceB'
Attempts:
2 left
💡 Hint

Remember that Angular injects the instance of ServiceA into ServiceB automatically.

❓ lifecycle
intermediate
1:30remaining
When is the injected service instance created in Angular?

Consider two services where ServiceB injects ServiceA. When is the instance of ServiceA created by Angular?

AOnly when <code>ServiceA</code> is explicitly instantiated with <code>new</code>
BAt application startup before any component loads
CWhen <code>ServiceB</code> is instantiated for the first time
DWhen the component that uses <code>ServiceA</code> is destroyed
Attempts:
2 left
💡 Hint

Think about Angular's lazy instantiation of services provided in root.

🔧 Debug
advanced
2:30remaining
Why does this Angular service injection cause a cyclic dependency error?

Examine the following code snippet. Why does Angular throw a cyclic dependency error?

Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ServiceA {
  constructor(private serviceB: ServiceB) {}
}

@Injectable({ providedIn: 'root' })
export class ServiceB {
  constructor(private serviceA: ServiceA) {}
}
ABecause ServiceA and ServiceB inject each other directly, creating an infinite loop
BBecause Angular services cannot inject other services
CBecause the services are missing @Injectable decorators
DBecause ServiceB is not provided in any module
Attempts:
2 left
💡 Hint

Think about what happens when two services depend on each other directly.

📝 Syntax
advanced
1:30remaining
Which option correctly injects ServiceA into ServiceB in Angular?

Choose the correct syntax for injecting ServiceA into ServiceB using Angular's dependency injection.

Aconstructor(private serviceA: ServiceA) {}
Bconstructor(serviceA: ServiceA) { this.serviceA = serviceA; }
Cconstructor(private serviceA) {}
Dconstructor(@Inject(ServiceA) serviceA) { this.serviceA = serviceA; }
Attempts:
2 left
💡 Hint

Remember how Angular uses TypeScript's constructor shorthand for dependency injection.

❓ state_output
expert
2:30remaining
What is the value of ServiceB.counter after these calls?

Given these Angular services, what is the value of ServiceB.counter after calling ServiceB.increment() twice?

Angular
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ServiceA {
  count = 0;
  increment() {
    this.count++;
  }
}

@Injectable({ providedIn: 'root' })
export class ServiceB {
  counter = 0;
  constructor(private serviceA: ServiceA) {}

  increment() {
    this.serviceA.increment();
    this.counter = this.serviceA.count;
  }
}

// Assume ServiceB.increment() is called twice
A0
B1
CThrows an error
D2
Attempts:
2 left
💡 Hint

Track how ServiceA's count changes and how ServiceB updates its counter.

Practice

(1/5)
1. What is the main purpose of service-to-service injection in Angular?
easy
A. To allow one service to use another service's functionality easily
B. To create multiple instances of the same service
C. To directly manipulate the DOM inside a service
D. To replace components with services

Solution

  1. Step 1: Understand service-to-service injection concept

    Service-to-service injection allows one service to use another service's methods or data by injecting it via the constructor.
  2. Step 2: Identify the purpose

    This helps keep code clean and reusable by sharing logic between services without duplication.
  3. Final Answer:

    To allow one service to use another service's functionality easily -> Option A
  4. Quick Check:

    Service-to-service injection = sharing logic between services [OK]
Hint: Services inject other services to share logic easily [OK]
Common Mistakes:
  • Thinking services create multiple instances by injection
  • Confusing services with components for DOM manipulation
  • Believing injection replaces components with services
2. Which syntax correctly injects a service named LoggerService into another service's constructor?
easy
A. constructor(LoggerService private logger) {}
B. constructor(private LoggerService logger) {}
C. constructor(private logger: LoggerService) {}
D. constructor(logger: LoggerService private) {}

Solution

  1. Step 1: Recall Angular constructor injection syntax

    Angular uses TypeScript constructor parameters with access modifiers (like private) followed by the variable name and type.
  2. Step 2: Match correct syntax

    The correct form is constructor(private logger: LoggerService) {}. Other options have incorrect order or missing keywords.
  3. Final Answer:

    constructor(private logger: LoggerService) {} -> Option C
  4. Quick Check:

    Access modifier + variable name + type = correct injection [OK]
Hint: Use 'private varName: ServiceType' in constructor [OK]
Common Mistakes:
  • Placing 'private' after the variable name
  • Swapping variable name and type order
  • Omitting access modifier like private or public
3. Given these services, what will DataService.getData() return?
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class LoggerService {
  log() { return 'Logged'; }
}

@Injectable({ providedIn: 'root' })
export class DataService {
  constructor(private logger: LoggerService) {}
  getData() {
    return this.logger.log() + ' Data';
  }
}
medium
A. Error: logger is undefined
B. 'Data Logged'
C. 'Logged'
D. 'Logged Data'

Solution

  1. Step 1: Understand service injection and method calls

    DataService injects LoggerService and calls its log() method, which returns 'Logged'.
  2. Step 2: Analyze getData() return value

    getData() returns the string from logger.log() plus ' Data', so the result is 'Logged Data'.
  3. Final Answer:

    'Logged Data' -> Option D
  4. Quick Check:

    Injected method output + ' Data' = 'Logged Data' [OK]
Hint: Injected service method output concatenated with string [OK]
Common Mistakes:
  • Assuming logger is undefined due to missing initialization
  • Mixing order of concatenated strings
  • Forgetting to call the log() method
4. What is wrong with this service-to-service injection code?
@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private authService: AuthService) {}
}

// AuthService is not decorated with @Injectable
medium
A. UserService must be provided in a module, not root
B. AuthService must be decorated with @Injectable to be injected
C. Constructor should not have access modifier
D. UserService should not inject any service

Solution

  1. Step 1: Check injection requirements

    Angular requires any service to be decorated with @Injectable to be injectable into other services or components.
  2. Step 2: Identify missing decorator

    AuthService lacks @Injectable, so Angular cannot inject it into UserService.
  3. Final Answer:

    AuthService must be decorated with @Injectable to be injected -> Option B
  4. Quick Check:

    @Injectable missing on injected service = error [OK]
Hint: Always add @Injectable to services used for injection [OK]
Common Mistakes:
  • Thinking access modifier in constructor is wrong
  • Believing services can't be provided in root
  • Assuming services can't inject other services
5. You have two services: ApiService and CacheService. You want ApiService to use CacheService to store data before returning it. Which is the best way to implement this service-to-service injection pattern?
hard
A. Inject CacheService into ApiService constructor and call cache methods inside ApiService
B. Inject ApiService into CacheService and call API methods inside CacheService
C. Create a third service that duplicates both ApiService and CacheService methods
D. Use global variables to share data between ApiService and CacheService

Solution

  1. Step 1: Understand service responsibilities

    ApiService handles API calls, CacheService handles data storage. ApiService should use CacheService to store data.
  2. Step 2: Apply service-to-service injection

    Inject CacheService into ApiService's constructor, then call CacheService methods inside ApiService to store data before returning it.
  3. Step 3: Avoid bad patterns

    Injecting ApiService into CacheService or duplicating methods breaks separation of concerns. Using global variables is bad practice.
  4. Final Answer:

    Inject CacheService into ApiService constructor and call cache methods inside ApiService -> Option A
  5. Quick Check:

    Inject dependent service into main service for clean logic [OK]
Hint: Inject helper service into main service, not vice versa [OK]
Common Mistakes:
  • Injecting main service into helper service causing circular dependency
  • Duplicating logic instead of reusing services
  • Using global variables instead of injection
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