Creating an injectable service is the first part of the dependency injection (DI) system in Angular. How do you inject a service into a component? Angular has a convenient function called inject() that can be used in the proper context.
NOTE: Injection contexts are beyond the scope of this tutorial, but you can learn more in the dependency injection (DI) essentials guide and DI context guide.
In this activity, you'll learn how to inject a service and use it in a component.
It is often helpful to initialize class properties with values provided by the DI system. Here's an example:
@Component({...})class PetCareDashboard { petRosterService = inject(PetRosterService);}
-
Inject the
CarServiceIn
app.ts, using theinject()function inject theCarServiceand assign it to a property calledcarServiceNOTE: Notice the difference between the property
carServiceand the classCarService. -
Use the
carServiceinstanceCalling
inject(CarService)gave you an instance of theCarServicethat you can use in your application, stored in thecarServiceproperty.Initialize the
displayproperty with the following implementation:display = this.carService.getCars().join(' ⭐️ '); -
Update the
ApptemplateUpdate the component template in
app.tswith the following code:template: `<p>Car Listing: {{ display }}</p>`,
You've just injected your first service into a component - fantastic effort.