Services Explained - Dependency Injection, Reusable Logic
What is a Service in Angular
A service is an Angular feature used to store common data, logic, and functions.
It helps share data between multiple components.
Example:
User details like name, email, phone, address are needed on many pages such as home, profile, and settings.
Instead of writing the same data again and again, we keep it in one service.
Why Services are Important
If data changes, you update it in one place only.
Code becomes reusable.
Components stay small and clean.
Logic and UI stay separate.
API calls are always done inside services.
Without services, every component will have its own copy of data and logic, which makes the project hard to manage.
Creating a Service (Command)
This creates:
- product.service.ts
- product.service.spec.ts
Common data, functions, and API calls are written inside the service file.
Product Service Code
Constructor is used only for initialization.
It does not return data.
Data is returned using a function.
Using Service in Component (Import Style)
Injecting Service in Component
@Injectable allows the service to be injected into any component.
Loading Data from Service
Service function is called using the service instance.
Returned data is stored in a variable.
HTML Code to Display Data
Data is shown only when button is clicked.
Products are displayed using loop and interpolation.