In this tutorial, we will learn how to use Angular Services to share data across components. Data sharing is a common necessity in web applications, and Angular Services provide an efficient way to achieve this.
By the end of this tutorial, you will be able to:
Prerequisites:
Before starting this tutorial, you should have a basic understanding of:
Angular Services are singleton objects that get instantiated only once during the lifetime of an application. They contain methods that maintain data throughout the life of an application, i.e., data is not refreshed and is persistent.
Here is how you can create and use a service to share data in Angular:
Create a Service: Use Angular CLI to generate a service.
ng generate service DataService
This command generates a service named DataService
.
Implement Data Sharing Method: Inside data.service.ts
, implement a method to share data.
```typescript
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: string[] = [];
setData(id: number, data: string) {
this.data[id] = data;
}
getData(id: number) {
return this.data[id];
}
}
``
This service has
setDataand
getData` methods to set and get data respectively.
Inject and Use the Service: Inject this service in any component and use it to share data.
```typescript
import { DataService } from './data.service';
export class AppComponent {
constructor(private dataService: DataService) {}
setData() {
this.dataService.setData(1, 'This is some data');
}
getData() {
console.log(this.dataService.getData(1));
}
}
```
setData
and getData
methods are used to set and get data.
// data.service.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private messageSource = new BehaviorSubject('default message');
currentMessage = this.messageSource.asObservable();
constructor() { }
changeMessage(message: string) {
this.messageSource.next(message);
}
}
// component1.ts
import { Component } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-component1',
template: `
<button (click)="newMessage()">New Message</button>
`,
styleUrls: ['./component1.component.css']
})
export class Component1Component {
constructor(private data: DataService) { }
newMessage() {
this.data.changeMessage("Hello from Component 1");
}
}
// component2.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";
@Component({
selector: 'app-component2',
template: `
{{message}}
`,
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
message:string;
constructor(private data: DataService) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message);
}
}
The DataService
holds the data, Component1Component
sets the data, and Component2Component
gets the data.
In this tutorial, you learned about Angular Services and how to use them to share data between components. We created a service using Angular CLI, implemented methods to set and get data, and injected the service into a component to share data.
As next steps, you may want to explore more about Angular Dependency Injection, Observables and Subjects, and other advanced Angular topics.
Exercise 1: Create a service to share data across three different components. Component1 sets the data, Component2 modifies it, and Component3 gets the data.
Exercise 2: Explore BehaviorSubject in Angular and use it in a service to share data.
Tip: BehaviorSubject is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:
next()
.onNext
.getValue()
method.Unique features of a subject compared to an observable are:
In addition, you can get an observable from behavior subject using the asObservable()
method on BehaviorSubject.
Solution: A basic solution has been shown in Code Examples section. Try to modify it according to the requirements of the exercises.