Exercise
This exercise demonstrates how to communicate a message from one component to another by using RxJs Subject.
- Create a home component and add 2 buttons. THe first button named ‘Send Message’ will call sendMessage() to broadcast a message. The second button named ‘Clear Message’ will call clearMessage() to clear the message.
- Create an app component and add a placeholder to display a message. Listen to the message from the home component and display it in the placeholder.
- Create a message service that will contain the following functions:
- sendMessage
- clearMessage
- getMessage
Hints: Use Subject
Solution
homecomponent.html
1
2
<button (click)="sendMessage()" class="btn btn-primary">Send Message</button>
<button (click)="clearMessage()" class="btn btn-secondary">Clear Message</button>
homecomponent.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { Component } from '@angular/core';
import { MessageService } from '../_services/index';
@Component({ templateUrl: 'home.component.html' })
export class HomeComponent {
constructor(private messageService: MessageService) { }
sendMessage(): void {
// send message to subscribers via observable subject
this.messageService.sendMessage('Broadcasting a message');
}
clearMessage(): void {
// clear message
this.messageService.clearMessage();
}
}
app.component.html
1
<div *ngIf="message" class="alert alert-success"></div>
app.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { MessageService } from './_services/index';
@Component({
selector: 'app',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnDestroy {
message: any;
subscription: Subscription;
constructor(private messageService: MessageService) {
// subscribe to home component messages
this.subscription = this.messageService.getMessage().subscribe(message => { this.message = message; });
}
ngOnDestroy() {
// unsubscribe to ensure no memory leaks
this.subscription.unsubscribe();
}
}
Code explained:
getMessage from messageService returns an observable. By subscribing to it, we get notified whenever a message is sent.
message.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class MessageService {
private subject = new Subject<any>();
sendMessage(message: string) {
this.subject.next({ text: message });
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}