在 Angular 中使用组件提供者数组的依赖注入的范围问题

Scope issue using dependency injection of a component's providers' array in Angular

是否可以使用提供者的组件数组向另一个服务提供服务?

我尝试以这种方式注入服务,但没有成功。

这是我提供服务的组件。

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{ provide: EXAMPLE_TOKEN, useClass: ExampleService }]  <---- this doesn't work as expected
})
export class AppComponent {
}

这是一个组件,它使用了我试图注入上面定义的令牌的服务。

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
})
export class ExampleComponent {
  constructor(private parentService: ParentService) { }
}

这里我使用了应用组件中定义的令牌。

@Injectable({ providedIn: 'root' })
export class ParentService {
  constructor(@Inject(EXAMPLE_TOKEN) private conf: ExampleService) { }  <---- throws error
}

我正在尝试找到一种方法来明智地提供服务组件,而无需使用模块提供程序。这有可能实现吗?

应该可以做到,但我认为这不起作用,因为您在 root 注入器(带有 providedIn: 'root')中提供了 ParentService。如果你删除它,并在 ExampleComponentproviders 数组中提供 ParentService,那么你的服务将由组件注入器提供,并且 angular 将遍历组件注入器树一直到你的 AppComponent 并从那里解析你的 EXAMPLE_TOKEN。如果您在 root 注入器中提供服务,它只会尝试使用根注入器和平台注入器来解决依赖关系。

服务:

@Injectable()
export class ParentService {
  constructor(@Inject(EXAMPLE_TOKEN) private conf: ExampleService) { }
}

组件:

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css'],
  providers: [ParentService],
})
export class ExampleComponent {
  constructor(private parentService: ParentService) { }
}

编辑:

Angular 尝试在元素注入器级别 (ExampleComponent) 解析 ParentService,然后一直导航树直到根元素注入器 (AppComponent ) 但 AppComponent 不提供 ParentService。然后它开始遍历模块注入器树,并在 root 注入器中找到 ParentService。但是在那个级别(根注入器级别)没有 EXAMPLE_TOKEN 的提供程序,这就是初始化失败的原因,我的回答有帮助。在我的代码片段中,Angular 将在创建 ParentService 时尝试使用元素注入器,并且它将成功地在根元素注入器中找到 EXAMPLE_TOKEN 依赖项。