Sharing Data Between Components
Angular Services can be used to share data between different components. A shared service can store information and provide methods that multiple components can use.
What Does Sharing Data Mean?
In Angular applications, different components may need access to the same information.
Instead of keeping duplicate copies of the same data in multiple components, a service can maintain the shared information and provide methods for reading and updating it.
Simple Definition
Data sharing through a service means storing common information in a reusable service so that multiple components can access it.
Sharing Data Flow
Why Share Data Through a Service?
Common Data
Keep information that is required by multiple components in one place.
Shared State
Reusable
Different components can reuse the same service.
Reuse
Centralized Data
Keep related data management inside a single service.
Centralized
Clean Components
Components can focus on their own UI responsibilities.
Separation
1. Creating a Shared Data Service
First, create a service that contains the data which needs to be shared.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SharedCourseService {
selectedCourse = '';
setCourse(course: string): void {
this.selectedCourse = course;
}
getCourse(): string {
return this.selectedCourse;
}
}
How it works
The service keeps the selected course in one common property. One component can update it using setCourse() and another component can read it using getCourse().
2. Updating Shared Data from Component A
The first component can update the shared data through the service.
import { Component } from '@angular/core';
import { SharedCourseService }
from './shared-course.service';
@Component({
selector: 'app-course-list',
templateUrl: './course-list.component.html'
})
export class CourseListComponent {
constructor(
private sharedCourseService: SharedCourseService
) {
}
selectCourse(course: string): void {
this.sharedCourseService.setCourse(course);
}
}
<button
class="btn btn-primary"
(click)="selectCourse('Java Full Stack')">
Select Java Full Stack
</button>
The selected course is stored inside the shared service.
3. Reading Shared Data in Component B
Another component can use the same service to read the shared data.
import { Component, OnInit } from '@angular/core';
import { SharedCourseService }
from './shared-course.service';
@Component({
selector: 'app-course-details',
templateUrl: './course-details.component.html'
})
export class CourseDetailsComponent implements OnInit {
selectedCourse = '';
constructor(
private sharedCourseService: SharedCourseService
) {
}
ngOnInit(): void {
this.selectedCourse =
this.sharedCourseService.getCourse();
}
}
<h3>
Selected Course
</h3>
<p>
{{ selectedCourse }}
</p>
4. Complete Shared Data Flow
5. Sharing Data with Multiple Components
The same shared service can be injected into multiple components.
@Injectable({
providedIn: 'root'
})
export class TrainingService {
selectedCourse = '';
setCourse(course: string): void {
this.selectedCourse = course;
}
getCourse(): string {
return this.selectedCourse;
}
}
6. Sharing Multiple Values
A service can store more than one value when multiple pieces of application information need to be shared.
@Injectable({
providedIn: 'root'
})
export class TrainingService {
selectedCourse = '';
trainingMode = '';
trainerName = '';
setDetails(
course: string,
mode: string,
trainer: string
): void {
this.selectedCourse = course;
this.trainingMode = mode;
this.trainerName = trainer;
}
getDetails(): any {
return {
course: this.selectedCourse,
mode: this.trainingMode,
trainer: this.trainerName
};
}
}
Course: Full Stack .NET
Training Mode: Offline
Trainer: CIIT Trainer
7. Sharing Data Dynamically
When components need to react when shared data changes, a service can expose an Observable-based value.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TrainingService {
private courseSubject =
new BehaviorSubject<string>('');
course$ =
this.courseSubject.asObservable();
setCourse(course: string): void {
this.courseSubject.next(course);
}
}
ngOnInit(): void {
this.trainingService.course$
.subscribe(course => {
this.selectedCourse = course;
});
}
How it works
The service publishes the latest selected course. Components subscribed to that shared value can receive updated data.
Data Sharing Approaches
| Approach | Use | Example |
|---|---|---|
| Service Property | Store common data |
selectedCourse
|
| Service Methods | Update or retrieve shared data |
setCourse()
|
| Observable | Notify components about data changes |
course$
|
| BehaviorSubject | Maintain and emit the latest value |
BehaviorSubject
|
Complete CIIT Training Institute Example
Suppose the CIIT Training Institute website has a course selection page and a course summary section. When a user selects a course, another component should be able to read the selected course.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CourseSelectionService {
private selectedCourse = '';
setSelectedCourse(course: string): void {
this.selectedCourse = course;
}
getSelectedCourse(): string {
return this.selectedCourse;
}
}
import { Component } from '@angular/core';
import { CourseSelectionService }
from './course-selection.service';
@Component({
selector: 'app-course-selection',
templateUrl: './course-selection.component.html'
})
export class CourseSelectionComponent {
constructor(
private courseSelectionService:
CourseSelectionService
) {
}
selectCourse(course: string): void {
this.courseSelectionService
.setSelectedCourse(course);
}
}
<h3>
Select a Course
</h3>
<button
class="btn btn-primary me-2"
(click)="selectCourse('Java Full Stack')">
Java Full Stack
</button>
<button
class="btn btn-primary"
(click)="selectCourse('Python Full Stack')">
Python Full Stack
</button>
import { Component, OnInit } from '@angular/core';
import { CourseSelectionService }
from './course-selection.service';
@Component({
selector: 'app-course-summary',
templateUrl: './course-summary.component.html'
})
export class CourseSummaryComponent implements OnInit {
selectedCourse = '';
constructor(
private courseSelectionService:
CourseSelectionService
) {
}
ngOnInit(): void {
this.selectedCourse =
this.courseSelectionService
.getSelectedCourse();
}
}
<h3>
Course Summary
</h3>
<p>
Selected Course:
{{ selectedCourse }}
</p>
Course Summary
Selected Course: Java Full Stack
Advantages of Sharing Data Through Services
- Multiple components can access common information.
- Data management can be centralized in one service.
- Components become simpler and more focused.
- Repeated data logic can be avoided.
- Services can provide reusable methods for reading and updating data.
- Observable-based services can notify components about changes.
Sharing Data Best Practices
- Keep shared data related to a clear application responsibility.
- Use meaningful service and property names.
- Avoid unnecessary duplication of the same data across components.
- Use service methods to control how shared data is updated.
- Use Observable-based patterns when components need to react to changing shared data.
- Keep business logic inside services instead of spreading it across multiple components.
Summary
Angular Services provide a convenient way to share data between different components by keeping common information inside a reusable service.
Components can update and read shared data through service methods, while Observable-based approaches can be used when components need to react to data changes.