Using the service in components - lordoftheflies/angular-essential-training GitHub Wiki
Let's see how we can use the media item service from within a component. In the media-item-list.component.ts file, we want to create the import statement for the service. Then we need to create a constructor function so we can have Angular do constructor injection. We give that a private parameter named mediaItemService and set the type to MediaItemService. Then we can make use of the onInit lifecycle event by importing onInit from Angular Core and declaring that the class implements onInit. Then we can add an ngOnInit method and set the media items property of the component class equal to a call to this.mediaItemService.get. And now we can delete the sample data from here. This component class has the onMediaItemDelete function so we can fill out the body of that with a call to this.mediaItemService.delete and pass it in the media item it receives. Finally, we can head over to the media-item-form.component.ts file then import the service at the top then add it to the constructor parameters, setting it as private just like we did in the list component. And now we can use it in the onSubmit method to add the media item through the add method of the service. So over in the browser, we see the list loaded and if we remove an item, we see the list change. And if we add an item we can see the list update as expected.