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 find more information in the Angular Docs if you would like to learn more.
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 PetCareDashboardComponent { petRosterService = inject(PetRosterService);}
-
Inject the
CarServiceIn
app.component.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.In the
constructorfunction of theAppComponent, add the following implementation:constructor() { this.display = this.carService.getCars().join(' ⭐️ ');} -
Update the
AppComponenttemplateUpdate the component template in
app.component.tswith the following code:template: `<p>Car Listing: {{ display }}</p>`,
You've just injected your first service into a component - fantastic effort. Before you finish this section on DI, you'll learn an alternative syntax to inject resources into your components.