Blog>
Snippets

Passing Data to a Remote Micro-Frontend

Explain how to pass data to a lazy-loaded micro-frontend using Angular services or component inputs.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedDataService {
  private dataSource = new BehaviorSubject<any>(null);
  data = this.dataSource.asObservable();

  constructor() { }

  updateData(data: any) {
    this.dataSource.next(data);
  }
}
An Angular service is created using Injectable. It utilizes a BehaviorSubject to hold and stream data across different components, including micro-frontends. The updateData method allows external components to update the data, which will subsequently be emitted to any subscribers.
// In the micro-frontend module
import { Component, OnInit, Input } from '@angular/core';
import { SharedDataService } from './shared-data.service';

@Component({
  selector: 'app-remote-component',
  template: `<div>{{data}}</div>`,
  styleUrls: ['./remote-component.component.css']
})
export class RemoteComponent implements OnInit {
  @Input() externalData: any;
  data: any;

  constructor(private sharedDataService: SharedDataService) {}

  ngOnInit() {
    if (this.externalData) {
      this.data = this.externalData;
    } else {
      this.sharedDataService.data.subscribe(newData => {
        this.data = newData;
      });
    }
  }
}
A component in a micro-frontend subscribes to data from SharedDataService upon initialization using ngOnInit. It also accepts data passed directly via @Input(), allowing two ways to receive data: from the shared service or directly as an input property.
// In the host application component
import { Component } from '@angular/core';
import { SharedDataService } from './shared-data.service';

@Component({
  selector: 'app-host-component',
  template: `<app-remote-component [externalData]='data'></app-remote-component>`,
  styleUrls: ['./host-component.component.css']
})
export class HostComponent {
  data = { message: 'Hello from host!' };

  constructor(private sharedDataService: SharedDataService) {}

  sendDataToRemote() {
    this.sharedDataService.updateData(this.data);
  }
}
Host application component includes the remote component and sets its input with data. It uses the SharedDataService to update the observable that the remote component subscribes to in order to pass data to the lazily loaded micro-frontend.