Building and providing a service - lordoftheflies/angular-essential-training GitHub Wiki
Let's create a service class for the MediaItems. We start by creating a new media-item.service.ts file in the app folder. Since we are planning to use this service elsewhere we need to export the class. So let's export class named MediaItemService. The first thing we can do with this service is move the static list of MediaItems into it. Those are located in the MediaItemListComponent. So let's switch to that and copy the MediaItems, property and value. Switch back over to the new service and paste it in there. We need some methods to work with this data. So let's add a get, add and delete method. The get method can return the MediaItems. The add can take in a MediaItem and push it onto the MediaItems array. And the delete method can take in a MediaItem and find the index of the MediaItem in the list. And if there is an index found it can splice it out of the list. With the service built we need to let the AppModule know that it is available. We can do that over in the app.module.ts file. First, we want to add the import statement to bring in the MediaItem service type. To make services available to the angular modules, you need to provide them. The NgModule Metadata has support for a property named providers. So we can add a provider's property onto the object literal that is being passed into the NgModule decorator. And we can set that to an array. Then we can add the MediaItemService to that array. This will tell angular to instantiate an instance of this service for use by things in this NgModule and any NgModules down the tree. And note that at this point we have just created a new service and provided it into the application. We have yet to make use of it. Which we will do in an upcoming video.