The messageservice code is as follows:
import { Injectable } from '@angular/core';import { Subject } from 'rxjs';@Injectable({ providedIn: 'root'})export class MessageService { private messageSource = new Subject<string>(); message$ = this.messageSource.asObservable(); messageAction(name: string) { this.messageSource.next(name); }}
The code of the message sending component is as follows:
TS
import { Component} from '@angular/core';import { MessageService } from '../service/message.service';@Component({ selector: 'app-send', templateUrl: './send.component.html', styleUrls: ['./send.component.css']})export class SendComponent { constructor(private messageService: MessageService) { } sendMessage(action: string) { this.messageService.messageAction(action); }
Html
<input #action><button (click)="sendMessage(action.value)">action</button>
Message receiving component
TS
Import {component, oninit, ondestroy} from '@ angular/core'; import {messageservice} from '. /service/message. service '; @ component ({selector: 'app-root', templateurl :'. /app.component.html ', styleurls :['. /app.component.css ']}) Export class appcomponent implements oninit, ondestroy {Action: string; Sub: subparts; ngoninit (): void {This. messageservice. message $. subscribe (Action => This. action = action);} ngondestroy (): void {This. sub. unsubscribe (); // do not forget to cancel the subscription} Constructor (Private messageservice: messageservice ){}
Angular service for component communication