Injectable & Providers — Series 3

Preview — 3 of 10 questions

How does 'any' differ from the usual 'root'?

javascript
@Injectable({ providedIn: 'any' })
export class LoggerService {}
A'any' behaves exactly like 'root' in every scenario
B'any' means the service can only be injected inside @Injectable()-decorated classes, never components
C'any' gives every eagerly-loaded part of the app one shared instance, same as 'root' — but each separately lazy-loaded module gets its own instance instead of sharing the app-wide one
D'any' disables tree-shaking, guaranteeing the service is always included in the bundle

HeaderComponent and CartPageComponent are unrelated siblings, each injecting CartService in their own constructor. CartPageComponent sets itemCount = 3. What does HeaderComponent see?

javascript
@Injectable({ providedIn: 'root' })
export class CartService {
  itemCount = 0;
}
AitemCount is 3 in HeaderComponent too — providedIn: 'root' means both components received references to the exact same, single CartService instance, so mutating it from anywhere is visible everywhere it's injected
BitemCount is still 0 in HeaderComponent — each component gets its own instance
CIt depends on which component was created first
DHeaderComponent needs to call ngOnChanges before it sees the update

What does writing private directly in the constructor parameter list accomplish, beyond just declaring a parameter?

javascript
constructor(private http: HttpClient) {}
AIt has no special effect beyond typing the parameter; this.http still needs to be assigned manually
BIt makes HttpClient a private, unshared instance just for this class
CThis is a TypeScript feature (parameter properties), not something Angular-specific — writing an access modifier (private, public, protected, or readonly) directly on a constructor parameter automatically declares a class field of that name and assigns the constructor argument to it, in one line, instead of requiring a separate field declaration plus this.http = http;
Dprivate here tells Angular's DI system to skip injecting the actual HttpClient and use a mock instead

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.