You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Angular Native Federation将宿主应用的TokenService共享给远程微前端应用?

如何通过Angular Native Federation将宿主应用的TokenService共享给远程微前端应用?

你好呀!你的思路其实已经走对了大半——通过Native Federation暴露宿主的TokenService给远程用是最符合Angular生态的方案,我来帮你把细节补全,让这个方案跑通:

1. 确认宿主应用的暴露配置(你已经做对了,再核对下)

你在宿主的federation.config.js里的exposes配置完全正确:

exposes: {
  './TokenService': './src/app/shared/token.service.ts'
}

这里要注意你的服务类名是Token(不是TokenService),这个后面远程导入的时候要对应上,别搞混了。

另外你设置了shared里的singleton: true,这个非常关键——它保证远程应用使用的是宿主的同一个TokenService实例,而不是自己新建一个,这样才能拿到宿主里的真实token。

2. 远程应用的导入与使用(核心步骤)

远程应用不需要额外修改federation.config.js,shareAll已经帮你处理了共享依赖的识别。接下来要在远程的组件里正确注入并使用这个服务:

第一步:在远程组件中导入宿主的Token服务

import { Component } from '@angular/core';
// 注意这里的类名是Token,和宿主导出的类名一致
import { Token } from 'mfe-host/TokenService';

第二步:通过Angular依赖注入使用服务

别手动new Token()!Angular的服务要通过构造器注入,这样才能拿到宿主的单例实例:

@Component({
  selector: 'remote-root',
  template: `<div>
    <h3>Remote App</h3>
    <p>Token from Host: {{ currentToken }}</p>
  </div>`
})
export class RemoteComponent {
  currentToken: string;

  // 注入宿主的Token服务
  constructor(private hostTokenService: Token) {
    // 调用服务的getToken方法获取值
    this.currentToken = this.hostTokenService.getToken();
  }
}

3. 处理动态Token的情况(进阶优化)

如果你的token是用户登录后才生成的(不是静态的"Hello world"),那需要让TokenService支持动态更新和远程监听。可以用RxJS的BehaviorSubject来实现:

改造宿主的TokenService:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class Token {
  // 用BehaviorSubject存储token,支持订阅更新
  private token$ = new BehaviorSubject<string>('');

  // 对外暴露可观察对象,供远程订阅
  get tokenObservable(): Observable<string> {
    return this.token$.asObservable();
  }

  getToken(): string {
    return this.token$.value;
  }

  // 登录后调用这个方法更新token
  setToken(newToken: string): void {
    this.token$.next(newToken);
  }
}

远程组件中监听Token变化:

export class RemoteComponent {
  currentToken: string;

  constructor(private hostTokenService: Token) {
    // 订阅token的变化,实时更新
    this.hostTokenService.tokenObservable.subscribe(token => {
      this.currentToken = token;
    });
  }
}

4. 新手常见排坑指南

  • 重启服务! 修改federation.config.js后,必须重启宿主和远程的Angular服务,否则配置不生效
  • 检查控制台错误:如果远程报"Cannot find module 'mfe-host/TokenService'",大概率是宿主的暴露路径写错了,或者宿主没启动
  • 确保单例配置:如果远程拿到的token和宿主不一致,检查宿主和远程的shared配置里singleton是不是true
  • 类名要对应:宿主导出的是class Token,远程导入时必须写import { Token } from ...,别写成TokenService

这样调整后,你就能在远程应用里稳定获取宿主的token啦~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 12:39:33