Angular's Dependency Injection System is a magic way to deliver the classes that house your business rules, or encapsulate other functionality, to your components. Here are three tips for using the dependency injector that are good to keep in mind as you learn, use, and master Angular.
1. Prefer ProvidedIn
When you create services, by default, use the ProvidedIn setting to put those services into the root injector. This gives you the safest, easiest and simplest way to create services. You won't forget to add them to your module, and this method works best for 99.9% of all use cases. It looks like this:
The string 'root' has to be exactly that. That registers your service, and lets you just keep coding, no need to open up your module file and add it there. Easy Peasy.
2. Learn useValue
We default to only using services that are "classes" meaning full-on, constructed classes with properties, methods, etc. But what if you have an object you got from somewhere that you'd like to use, such as from a 3rd party library, or a JSON file, or what if you want to inject just a single value, like a timeout value.
Or maybe a collection of values
There's no functionality here, so a class can be overkill. And if you get these values from somewhere else, you would need to then wrap them in a class.
To make this easier, you can just take single values, or simple objects, and create services out of them if you learn the useValue provider. You can find documentation on that here.
3. Non-Root Injection is a Code Smell
When creating services, registering them in the root injector is the default, which you can do using either the ProvidedIn syntax shown above, or by registering it in the providers section of your app.module file.
There are plenty of reasons to register a service somewhere else besides your root injector, and instead provide them in a component, a directive, or in a pipe. But whenever you use one of these methods, you should DEFINITELY understand what you're doing, and the ramifications of that decision. So always consider this method a code smell. If you are considering using it, double-check that you are making a good decision, and actually need to do that.
And there you have it: three tips for Angular's dependency injection.
Happy coding!
Signup for my newsletter here.
Visit Us: thinkster.io | Facebook: @gothinkster | Twitter: @gothinkster
Top comments (0)