When creating and using services in an Angular application, it is recommended to utilize dependency injection. Dependency injection is built into the Angular framework and can be implemented by following 3 easy steps.

1. Create a service
2. Decorate the service for injection
3. Inject the service

The easiest way to create a service is by sing the Angular CLI. Simply type:

ng g s nameOfService

There is no need to add the word “Service” at the end of the name of your service. This will be added for you automatcally by the Angular CLI

The Angular CLI will automatically decorate the newly created service class with the Injectable decorator. The decorator will provide the value of “root” for the providedIn property. This will instruct angular to register the service for use across the entire application. You can configure your service to be scoped at the component level by removing the providedIn property and adding the service class to the component’s providers property array.

@Injectable()[{
providedIn: ‘root’
}]

Finally, to use the service, simply request the service via the component’s constructor as an argument.

constructor(private titleService: TitleService){
}

Just like that, you now have services being created and injected into your components for use throughout your Angular application by using dependency injection.

Brian Lagunas

View all posts

Follow Me

Follow me on Twitter, subscribe to my YouTube channel, and watch me stream live on Twitch.