Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Current »

Info

A service is a component that is not linked to a view.  It is a standard class that provides services to the components, and it does not have to be injectable.  In the example that follows, we are going to make the service injectable.

Consider this basic service 

Notice the decorator, it marks this class as Injectable.  Now we need inject it in a desired component, see the section below.

Important

You must make sure your class is registered as a provider of a service.  This is done through the metadata in the @Injectable decorator declaration, the providedIn argument. 

When you provide the service at the root level, Angular creates a single, shared instance of HeroServiceand injects into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.


Injecting a Service

Make the changes to your code and see what happens when you run it (remember in this example, the HEROES entity is a predefined array of Hero objects).



  • No labels