如何在微前端架构中从主机到远程共享服务?

问题描述 投票:0回答:1

我的主机应用程序中有一项服务,我想在远程 (MFE) 应用程序中使用该服务。这两个应用程序托管在不同的存储库中

例如在我的远程应用程序中

this.hostAppService.help();

如何在两个应用程序之间共享此信息?任何状态或任何事情都不会通过此服务处理,只是一些简单的辅助函数。

关于如何做到这一点有什么想法吗?我在网上查了一下,似乎图书馆是一个选择,但我想避免这种情况。

angular frontend micro-frontend webpack-module-federation
1个回答
0
投票
If you're trying to invoke a method help() from hostAppService within a micro frontend application, you'll need to establish a communication mechanism between the micro frontend and the host application where hostAppService is defined.

Assuming you're using Angular, and hostAppService is provided by the host application, you can utilize Angular's dependency injection mechanism to inject hostAppService into your micro frontend component or service.

In your micro frontend component or service, inject hostAppService:
import { HostAppService } from 'path-to-host-app-service'; // Adjust the path accordingly

@Component({
  selector: 'app-micro-frontend',
  templateUrl: './micro-frontend.component.html',
  styleUrls: ['./micro-frontend.component.css']
})
export class MicroFrontendComponent implements OnInit {

  constructor(private hostAppService: HostAppService) { }

  ngOnInit(): void {
    // Call the help() method from hostAppService
    this.hostAppService.help();
  }
}
Make sure HostAppService is provided by the host application. You may need to include HostAppService in the providers array of a module that is shared between the host and the micro frontend.

@NgModule({
  ...
  providers: [HostAppService],
  ...
})
export class SharedModule { }

Ensure that help() method is defined in HostAppService within the host application:

@Injectable({
  providedIn: 'root'
})
export class HostAppService {

  constructor() { }

  help(): void {
    // Implementation of help() method
    console.log("Help method invoked from hostAppService.");
  }
}
By following these steps, you'll be able to invoke the help() method from hostAppService within your micro frontend application. Remember to handle any errors or edge cases that may arise, such as hostAppService not being available or failing to respond.
© www.soinside.com 2019 - 2024. All rights reserved.