Question presented to candidate:
"We are starting a new Angular 22 project and the team is split: half write constructor injection, half write inject(). Which should we standardise on, and are there cases where the other one is still the right call?"
What a strong answer should cover:
- A clear default:
inject()for new code. It is what the Angular docs, the CLI-generated@Service()decorator and functional APIs (guards, interceptors, resolvers, initializers) are built around. - Concrete reasons: works outside classes (reusable
injectX()helpers), nosuper(...)forwarding in subclasses, typed optional results, no dependence on compiler type metadata, and required by@Service()(constructor parameters are compile error NG2028). - Where constructor injection still fits: existing codebases with a consistent style, classes you want to
newdirectly in plain unit tests, and libraries supporting older Angular versions. - The cost of
inject(): it only runs in an injection context, so tests must create the class through an injector (TestBed,Injector.createorrunInInjectionContext). - Migration path:
ng generate @angular/core:injectconverts constructor injection automatically; do it per folder and keep one style per class.
Clarifying questions expected:
- "Is this greenfield, or are we converting an existing codebase?"
- "How are services unit tested today:
newwith fakes, or TestBed?"
Code / implementation expected: Optional — a reusable inject helper, and a test showing how each style is instantiated with a fake.