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

如何在Angular库中通过字符串注入指定服务?

Angular库通过字符串参数注入对应服务的解决方案

问题核心

你之前的尝试失败,本质是Angular注入系统依赖令牌的引用相等性:你定义的SERVICE_A是一个独立的InjectionToken对象,哪怕它的描述字符串是'ServiceA',直接用字符串'ServiceA'调用injector.get(),和这个令牌对象完全不是同一个匹配依据,所以找不到对应的服务提供者。

下面提供两种可行方案,其中第一种满足你“仅通过字符串令牌实现”的需求:


方案一:直接用字符串作为注入令牌(推荐)

修改应用端的服务配置,把字符串本身作为注入令牌:

// app.module.ts 或负责服务提供的模块
providers: [
  { provide: 'ServiceA', useClass: ServiceA },
  { provide: 'ServiceB', useClass: ServiceB }
]

然后在库中直接通过字符串参数获取服务:

// 库中的代码
import { Injector } from '@angular/core';
import { KnownInterface } from './your-known-interface-path';

constructor(private injector: Injector) {}

getTargetService(serviceName: string): KnownInterface {
  // 直接用字符串作为令牌获取
  return this.injector.get<KnownInterface>(serviceName);
}

调用示例:this.getTargetService('ServiceA'),此时注入系统会直接匹配到对应服务。


方案二:保留原有注入令牌,通过映射关联字符串

如果不想修改应用端的服务提供方式,可通过字符串与注入令牌的映射表来实现:

  1. 应用端创建映射关系:
// 应用端代码
import { SERVICE_A, SERVICE_B } from './your-tokens-path';

// 导出字符串到令牌的映射
export const SERVICE_NAME_TOKEN_MAP = {
  'ServiceA': SERVICE_A,
  'ServiceB': SERVICE_B
};
  1. 库中通过映射表获取令牌再注入服务:
// 库中的代码
import { Injector } from '@angular/core';
import { KnownInterface } from './your-known-interface-path';

constructor(private injector: Injector) {}

getTargetService(serviceName: string, tokenMap: Record<string, any>): KnownInterface {
  const targetToken = tokenMap[serviceName];
  if (!targetToken) {
    throw new Error(`未找到对应服务令牌:${serviceName}`);
  }
  return this.injector.get<KnownInterface>(targetToken);
}

应用端调用时传入映射表:

// 应用端调用库的代码
import { SERVICE_NAME_TOKEN_MAP } from './your-map-path';

const service = yourLibraryInstance.getTargetService('ServiceA', SERVICE_NAME_TOKEN_MAP);

内容的提问来源于stack exchange,提问作者PeterS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 18:27:42