CyanSill
再见夏日青鸟

cyansill

再见夏日青鸟

博客园 首页 新随笔 联系 订阅 管理

向 Service 注入另一 Service ,如下图

export class MemeService {
  public constructor(
    @Inject()
    private readonly anotherMemeService: AnotherMemeService,
    // ...
  ) {}
}

运行时出现错误,提示如:

Error: Token is undefined at index: 1. This often occurs due to circular dependencies.
Ensure there are no circular dependencies in your files or barrel files.
...
    at Object.<anonymous> (/to/path/service/meme.service.ts:*:*)

错误在该情况下并非提示中的所谓“循环依赖”引起,系因注入 Service 的 Inject 注解的 Token 参数为空,导致注入时无法找到目标类。
解决方案如下:

export class MemeService {
  public constructor(
    @Inject(AnotherMemeService) // or don't write this line // 或者不要写这一行,这种注入方式无需注解
    private readonly anotherMemeService: AnotherMemeService,
    // ...
  ) {}
}
posted on 2024-12-20 18:31  CyanSill  阅读(21)  评论(0)    收藏  举报