0
0
Angularframework~30 mins

Service scope (root, module, component) in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Angular Service Scopes: root, module, and component
📖 Scenario: You are building a simple Angular app that tracks how many times a button is clicked. You want to learn how Angular services can have different lifetimes depending on where they are provided: at the root, module, or component level.
🎯 Goal: Create an Angular service that counts clicks and explore how its scope changes when provided in root, a feature module, or a component. You will see how the count behaves differently depending on the service scope.
📋 What You'll Learn
Create a service called ClickCounterService with a count property and an increment() method.
Provide the service in the root injector in Step 2.
Create a feature module called FeatureModule and provide the service in this module in Step 3.
Provide the service in a component called ClickComponent in Step 4.
Observe how the click count behaves differently depending on the service scope.
💡 Why This Matters
🌍 Real World
Understanding service scope helps you manage shared data and state in Angular apps, avoiding bugs and improving performance.
💼 Career
Angular developers often need to decide where to provide services to control data sharing and component behavior effectively.
Progress0 / 4 steps
1
Create the ClickCounterService with count and increment method
Create an Angular service called ClickCounterService with a public property count initialized to 0 and a method increment() that increases count by 1.
Angular
Need a hint?

Use @Injectable() without parameters. Define count as a number starting at 0. The increment() method should add 1 to count.

2
Provide ClickCounterService in the root injector
Modify the ClickCounterService to be provided in the root injector by adding { providedIn: 'root' } inside the @Injectable() decorator.
Angular
Need a hint?

Add { providedIn: 'root' } inside @Injectable() to make the service singleton app-wide.

3
Provide ClickCounterService in a feature module
Create a feature module called FeatureModule and provide ClickCounterService in its providers array. Import NgModule from '@angular/core'.
Angular
Need a hint?

Use @NgModule decorator with a providers array including ClickCounterService. Export the class FeatureModule.

4
Provide ClickCounterService in a component
Create a component called ClickComponent with a providers array that includes ClickCounterService. Import Component from '@angular/core'.
Angular
Need a hint?

Use @Component with providers array including ClickCounterService. Inject the service in the constructor as public clickCounter. Use a button in the template that calls increment() and shows count.