Assignment #15 - Adding a Message Service We are going to add a service that all components can use to display messages on the web page Open Command Prompt making sure you are in the C:\Humor folder enter the command: ng generate service message you will see: C:\Humor>ng generate service message CREATE src/app/message.service.spec.ts (362 bytes) CREATE src/app/message.service.ts (136 bytes) Steps: 1) In Visual Code create src/app/messageHandler.ts it will be our Interface 2) Add these methods to the messageHandler Interface you will need to add any missing imports addMessage(message: Message) : void; 3) Edit the newly generated message.service.ts file We are going to use a special type of Observable call a Subject (specifically a BehaviorSubject) A Subject requires an initial value, and when you subscribe it returns the latest value, where a regular Observable will wait until there is a new value, and you will not get any values loaded before you subscribed this is what our Message.service.ts file should contain: import { Subject, BehaviorSubject } from 'rxjs'; import { Injectable } from '@angular/core'; import { MessageHandler } from './messageHandler'; import { Message } from './message'; @Injectable({ providedIn: 'root' }) export class MessageService implements MessageHandler { messageStream: Subject = new BehaviorSubject(new Message('', '')); constructor() { } public addMessage(message: Message) { this.messageStream.next(message); } } 4) Let's create a welcome message in our welcome.component.ts file we will use constructor injection to get Message Service (you will need to add theimports) export class WelcomeComponent implements OnInit { constructor(private messageService : MessageService) { } ngOnInit(): void { let message : Message = new Message("Welcome to the Humor Application", "info"); this.messageService.addMessage(message); } } notice the Message type of "info" will we use different CSS classes for different message types 5) Now we need to put message on to our page... in app.component.html we have a placehold for the message component
6) We will now use the message component to display our messages in the message.component.ts file: A) add the MessageService to the constructor B) create a field named message of type Message, itinialize it to an empty Message C) add this code in the constructor: this.messageService.messageStream.subscribe((val) => { this.message = val; }); D) add a new method to clear the Message like this: removeMessage(): boolean { this.messageService.addMessage(new Message('', '')); return false; } 7) Finally we get to the HTML that will display the Message in message.component.html put this code:
{{message.value}}
8) Notice the Angular directives to set the CSS styles based on the message type notice the Bootstrap styles to make a "Close" button, that will remove the message notice the whole
will not render if the message has no value 9) Save everything, run: ng serve and look at the Browser