Angular · Middle · Question 26 of 75
How do you inject a dependency that might not be provided?
- ✓Correct answer:
inject(Analytics, { optional: true }), which returnsnullinstead of throwing - 2
inject(Analytics) ?? null, which never throws - 3Wrap
injectintry/catchin the template
Explanation
Without optional, Angular throws NullInjectorError when no provider is found. Other options include self, skipSelf and host, which limit where the resolution looks.