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
CarService
In
app.component.ts
, using theinject()
function inject theCarService
and assign it to a property calledcarService
Note: Notice the difference between the property
carService
and the classCarService
. -
Use the
carService
instanceCalling
inject(CarService)
gave you an instance of theCarService
that you can use in your application, stored in thecarService
property.In the
constructor
function of theAppComponent
, add the following implementation:constructor() { this.display = this.carService.getCars().join(' ⭐️ ');}
-
Update the
AppComponent
templateUpdate the component template in
app.component.ts
with 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.