Providing services in the root - lordoftheflies/angular-essential-training GitHub Wiki

By making use of the provider's meta data property for the NG module decorator, we can declare what services we want to be included in the injector for that NG module. We did that with the media item service in the last video, adding it to the @module. Now, the @module is our root NG module for this application, meaning that is it the top level NG module. Registering that media item service in there was like registering it in the root injector. Angular has another way to wire up injectables to the root provider-- one that can be done without using the provider's meta data property for the NG module decorator. The @injectable decorator has a meta data property named 'providedIn' that can be used to tell Angular where the decorated service should be registered at. In the media-item.service.ts file, we can import the injectable decorator from @Angular/core. The we can decorate the media item service class with the @Injectable decorator, and pass it in an object literal with a property named providedIN, and set that to a string literal with a value of 'root'. With this set, Angular will instantiate a single instance of this service in the root injector, and will provide it to any class that ask for it in the application. If we know that we want to provide a service throughout our entire application, this is the preferred approach to registering it. Not only because it keeps the registration logic next to the service class itself, but it also provides an optimization opportunity for the Angular compiler. If this service is not actually requested in any other class constructor, the Angular compiler will exclude it from the build. While not that common, this can come into play in cases where we have a service that is used by an NG module that gets lazy loaded- something we will cover when we go over routing in Angular. Okay, now that we are telling Angular to register this media item service class at the root level, via the @Injectable provided in meta data property, we no longer need to include it in the provider's array in the NG module. So, let's head over to the app.module.ts file and we can remove the import statement, and then we can remove the provider's array with the media item service.