为了账号安全,请及时绑定邮箱和手机立即绑定

如何使用 angular 8 中的注入器注入使用注入令牌的服务

如何使用 angular 8 中的注入器注入使用注入令牌的服务

LEATH 2021-11-12 16:39:38
我正在开发一个由我公司的两个项目使用的包。在项目 A 中,只有在那里我们得到了这样提供的消息服务core.module:        {          provide: 'MESSAGE_SERVICE',          useClass: MessageService        }在我的组件中,我需要注入这个服务。我正在使用injector. 然而get,接受字符串作为参数的方法已被弃用,所以我不能使用它,尽管它可以工作。当我尝试使用新的 API 时,InjectionToken我总是未定义。这是我的代码:  protected messageService: any;  constructor(protected injector: Injector) {    const messageServiceInjectionToken = new InjectionToken('MESSAGE_SERVICE');     // i get null    this.messageService = this.injector.get<any>(messageServiceInjectionToken, null, InjectFlags.Optional);    // It works but method is deprecated    this.messageService = this.injector.get('MESSAGE_SERVICE', null);    // It works but I cannot use MessageService class directly as it is not present in application B    this.messageService = this.injector.get(MessageService);  }在不使用所述类的直接导入的情况下获得我的服务的正确方法是什么?我想在项目 B 中创建一个模拟类,这样我就可以使用MessageService类。但是,我想知道是否有更好的方法。编辑共享服务只是其他实现的基类,它是使用工厂提供的,因此其中没有依赖注入。这是它的提供方式:export function parentServiceFactory(platformService: PlatformService, injector: Injector) {  if (platformService.isIOS) {    return new IosChildService(injector);  }  if (platformService.isAndroid) {    return new AndroidChildService(injector);  }  return new DesktopChildService(injector);}@NgModule({providers: [    {      provide: ParentService,      useFactory: parentServiceFactory,      deps: [PlatformService, Injector]    }]})export class SharedModule {}
查看完整描述

2 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

该注入令牌的目的是能够不使用注入器。

代替 =,使用此语法

constructor(@Inject('MESSAGE_SERVICE')protected service: YourInterface)

尽管如果您提供服务,我看不到使用注入令牌的意义。


查看完整回答
反对 回复 2021-11-12
?
吃鸡游戏

TA贡献1829条经验 获得超7个赞

查看完整回答
反对 回复 2021-11-12
  • 2 回答
  • 0 关注
  • 123 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信