CodexBloom - Programming Q&A Platform

Angular 15: Dependency Injection Issue with Multi-Providers in Feature Module

👀 Views: 74 💬 Answers: 1 📅 Created: 2025-06-12
angular dependency-injection multi-providers TypeScript

I'm migrating some code and I'm relatively new to this, so bear with me. I'm encountering a strange issue with dependency injection in Angular 15 when using multi-providers in a feature module. I have a service that I'm trying to provide as a multi-provider, and it seems that the instances are not being injected correctly in my components. Specifically, I'm trying to inject an array of services into my component constructor, but I'm only getting one instance instead of all of them. Here's how I've set up my services: ```typescript // my-first.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', multi: true }) export class MyFirstService { constructor() { console.log('MyFirstService instance created'); } } // my-second.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', multi: true }) export class MySecondService { constructor() { console.log('MySecondService instance created'); } } ``` Then, in my feature module, I provide these services: ```typescript @NgModule({ providers: [MyFirstService, MySecondService], }) export class MyFeatureModule {} ``` In my component, I try to inject them like this: ```typescript import { Component, Inject } from '@angular/core'; import { MyFirstService } from './my-first.service'; import { MySecondService } from './my-second.service'; @Component({ selector: 'app-my-component', template: '<p>Check the console for instances!</p>', }) export class MyComponent { constructor(@Inject(MyFirstService) public firstService: MyFirstService[], @Inject(MySecondService) public secondService: MySecondService[]) { console.log(firstService); console.log(secondService); } } ``` When I run this code, I only see one instance of each service in the console, despite expecting an array of instances. I’ve verified that the `multi: true` option is indeed set, but it seems to be ignored in this context. I've also checked for any conflicting providers in my app module and other feature modules, but nothing stands out. Is there a specific way I'm supposed to handle multi-providers in this scenario? Any insights would be greatly appreciated! I'm working on a API that needs to handle this. Has anyone else encountered this? For context: I'm using Typescript on Windows 10. What am I doing wrong?