All quizzesEasy
Injectable & Providers — Series 2
Preview — 3 of 10 questions
HeroList needs HeroService. Why ask for it rather than construct it?
javascript
export class HeroList {
private heroes = inject(HeroService); // instead of new HeroService(new HttpClient(...))
}ABecause the component would otherwise have to know how to build the service and everything the service needs — and every test would have to build it too. Asking for it leaves construction to the injector, which is also what makes substitution possible
BBecause new is forbidden in Angular classes
CBecause new creates a copy of the service per change detection cycle
DBecause services must be created before the component exists
What does this achieve?
javascript
@Injectable({ providedIn: 'root' })
export class HeroService {}AA new instance per component that injects it
BRegistration only for the root component's subtree
COne instance for the whole application, created lazily on first injection — and if nothing injects it, the class can be dropped from the bundle entirely
DAn instance created eagerly at bootstrap, always
Which of these classes needs the decorator?
javascript
class Logger { log(m: string) { console.log(m); } }
class HeroService { constructor(private http: HttpClient) {} }AHeroService — a class Angular has to construct with dependencies needs the decorator, because that is what emits the constructor's type metadata. A dependency-free Logger provided by useClass can work without it, but decorating both is the convention
BNeither; the decorator is optional everywhere
CBoth, always, or the compiler errors
DLogger only, since it has no constructor parameters
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.