Blog>
Snippets

Implementing Cross-Application Communication

Showcase an implementation of a cross-micro-frontend communication system using Angular's EventEmitter or a shared service.
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class SharedService {
  private messageSource = new Subject<string>();

  message$ = this.messageSource.asObservable();

  sendMessage(message: string) {
    this.messageSource.next(message);
  }
}
Defines a shared service with a subject to multicast messages between components. Components can send messages via this service and also subscribe to messages.
import { Component } from '@angular/core';
import { SharedService } from './shared.service';

@Component({
  selector: 'app-sender',
  template: '<button (click)="sendMessage()">Send Message</button>',
})
export class SenderComponent {
  constructor(private sharedService: SharedService) {}

  sendMessage() {
    this.sharedService.sendMessage('Message from SenderComponent');
  }
}
Defines a sender component that uses the SharedService to send messages when the button is clicked.
import { Component, OnDestroy } from '@angular/core';
import { SharedService } from './shared.service';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-receiver',
  template: '<p>Received message: {{ message }}</p>',
})
export class ReceiverComponent implements OnDestroy {
  message: string = '';
  private subscription: Subscription;

  constructor(private sharedService: SharedService) {
    this.subscription = this.sharedService.message$.subscribe(
      (msg) => (this.message = msg)
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
Defines a receiver component that uses the SharedService to subscribe to messages. It shows the received messages and cleans up the subscription on destroy.