Given two Angular services where ServiceB injects ServiceA, what will be logged when ServiceB.logMessage() is called?
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
Remember that Angular injects the instance of ServiceA into ServiceB automatically.
ServiceB receives an instance of ServiceA via dependency injection. Accessing this.serviceA.message returns the string defined in ServiceA.
Consider two services where ServiceB injects ServiceA. When is the instance of ServiceA created by Angular?
Think about Angular's lazy instantiation of services provided in root.
Angular creates the instance of a service when it is first requested, such as when another service or component injects it.
Examine the following code snippet. Why does Angular throw a cyclic dependency error?
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) {} }
Think about what happens when two services depend on each other directly.
Angular cannot resolve dependencies when two services inject each other directly, causing a cyclic dependency error.
Choose the correct syntax for injecting ServiceA into ServiceB using Angular's dependency injection.
Remember how Angular uses TypeScript's constructor shorthand for dependency injection.
Option A uses the correct TypeScript shorthand to declare and assign the injected service as a private property.
Given these Angular services, what is the value of ServiceB.counter after calling ServiceB.increment() twice?
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
Track how ServiceA's count changes and how ServiceB updates its counter.
Each call to ServiceB.increment() calls ServiceA.increment(), increasing count by 1. After two calls, count is 2, so ServiceB.counter is set to 2.