Array containing multiple service providers in Angular

I encountered a problem while utilizing multiple providers in my application:

ERROR Error: No provider for Array!
at injectionError (VM634 core.umd.js:1238) [angular]
at noProviderError (VM634 core.umd.js:1276) [angular]
at ReflectiveInjector_._throwOrNull (VM634 core.umd.js:2777) [angular]
at ReflectiveInjector_._getByKeyDefault (VM634 core.umd.js:2816) [angular]
at ReflectiveInjector_._getByKey (VM634 core.umd.js:2748) [angular]
at ReflectiveInjector_.get (VM634 core.umd.js:2617) [angular]
at AppModuleInjector.NgModuleInjector.get (VM634 core.umd.js:3585) [angular]
at resolveDep (VM634 core.umd.js:11046) [angular]
at createClass (VM634 core.umd.js:10899) [angular]
at createDirectiveInstance (VM634 core.umd.js:10730) [angular]
at createViewNodes (VM634 core.umd.js:12093) [angular]
at createRootView (VM634 core.umd.js:11998) [angular]
at callWithDebugContext (VM634 core.umd.js:13213) [angular]
at Object.debugCreateRootView [as createRootView] (VM634 core.umd.js:12673) [angular]

Here is the code snippet causing the issue:

@Injectable()
abstract class OtherService<O> {
 
  protected parentProp: O;

  constructor() {
  }

}

@Injectable()
class OtherServiceImpl extends OtherService<any> {

  private prop; 

  constructor() {
    super();
  }
}

@NgModule({
})
class OtherModule {

  static forRoot(): OtherModule {
    return {
      ngModule: OtherModule,
      providers: [
        {provide: OtherService, useFactory: () => new OtherServiceImpl(), multi: true},
        {provide: OtherService, useFactory: () => new OtherServiceImpl(), multi: true} 
      ],
    };
  }
}

@Component({
  selector: 'app-root',
  template: `
    <pre>{{services | json}}</pre> 
  `
})
class AppComponent {
// IF I USE (public services: OtherService<any>) INSTEAD, IT WORKS, IT'S AND ARRAY BUT NOT USABLE AS AN ARRAY TYPE IN MY COMPONENT
  constructor(public services: OtherService<any>[]) {
  }
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    OtherModule.forRoot()
  ],
  bootstrap: [AppComponent]
})
class AppModule {
}

You can view a working example in this Plunker : https://plnkr.co/edit/Nui2eFwS3CtT1fYKDpzh?p=preview

Upon observing the above code, when I inject my multi services into the AppComponent, it only functions properly if I do not specify it as an array...however, it should be recognized as an array.

In TypeScript, this property is identified as an object and therefore cannot be iterated on...

Answer №1

It's not every day that I come across a request like this, it's quite unusual. However, after digging into it, I was able to set it up for you. To achieve this, don't forget to utilize @Inject() as shown below:

constructor(@Inject(OtherService)public services: OtherService<any>[])

Check out the example here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The arrow keys (up and down) are unresponsive when using mat-table in an Angular application

There seems to be an issue with my code. When I press the down arrow key for the first time, it goes to the next row as expected. However, when I press the down arrow key again, it does not function properly. (https://i.stack.imgur.com/4qznx.jpg) **HTML* ...

Display the customer's name using the Mat-Select display object property by fetching it from the previously selected or saved value

Having some difficulties with mat-select and options in my Angular 6 project. Here is the scenario I am facing: I would like to create a dropdown list of organizations where I can select one and save the complete organization object, not just its name. ...

Navigational assistance on the keyboard - Improving Accessibility

My situation involves selecting an option from a dropdown menu on X-page, which triggers the opening of Modal-1 while disabling the background. If a selection is made within Modal-1, it leads to Modal-2. I am facing two issues/questions: Upon opening Moda ...

Creating a distinct input for each row in a table using Angular 2

I am encountering an issue with inputs being created for each row in my PrimeNG/datatable. The problem arises from the local variable #itsmIncident, which causes confusion when trying to pass values to the "Save" button as there are multiple rows involve ...

Issue: The Karma plugin in Angular CLI >6.0 is now exported from "@angular-devkit/build-angular" instead

Issue: I'm encountering an error in Angular CLI version 6.0 or higher where the Karma plugin is now exported by "@angular-devkit/build-angular". // Below is the Karma configuration file, you can find more information at // module.exports = function ...

What is the reasoning behind defaultValue possessing the type of any in TextField Material UI?

According to the Material UI guidelines, the component TextField specifies that its defaultValue property accepts the type any. I decided to experiment with this a bit and found that in practice, defaultValue actually supports multiple types. You can see ...

Error in InversifyJs exclusively occurring in Internet Explorer

I'm currently utilizing Typescript with webpack for the development of a web application. Recently, I made the transition to using the inversifyJs DI library. However, I am encountering a specific error only when testing on Internet Explorer (version ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

invoke a specified function at runtime

I recently came across a useful library called https://github.com/ivanhofer/typesafe-i18n This library has the capability to generate strongly typed translation data and functions, as illustrated below. (the examples provided are simplified for clarity) e ...

Guide to developing a personalized useReducer with integrated decision-making and event activation

I am interested in creating a custom hook called useTextProcessor(initialText, props). This hook is designed for managing and manipulating text (string) within a React state. It utilizes useReducer to maintain a cumulative state. Here is the implementation ...

Positional vs Named Parameters in TypeScript Constructor

Currently, I have a class that requires 7+ positional parameters. class User { constructor (param1, param2, param3, …etc) { // … } } I am looking to switch to named parameters using an options object. type UserOptions = { param1: string // ...

Exploring NestJs: The Importance of DTOs and Entities

In my project, I'm currently experimenting with utilizing DTOs and Entities in a clever manner. However, I find it more challenging than expected as I develop a backend system for inventory management using NestJs and TypeOrm. When my client sends me ...

Having an empty string in an array used with *ngFor can lead to unusual positioning problems, unlike when the array contains non-empty strings

Check out this live demo to see it in action: https://stackblitz.com/edit/angular-5vwspd You might notice that the first 2 days are positioned strangely on the calendar. I'm currently working on a calendar component, and I am using an array called d ...

What is the method for including an input field beside the y-axis label in Chart.js?

I'm struggling to implement a live poll using Chart.js where users can select their option by checking a checkbox next to the y-axis label. My initial attempt was unsuccessful as placing the input boxes outside of the canvas led to alignment issues wi ...

What is the best way to create TypeScript declarations for both commonjs modules and global variables?

Wanting to make my TypeScript project compatible with both the commonjs module system and globals without modules. I'm considering using webpack for bundling and publishing it into the global namespace, but running into issues with the definitions (.d ...

Concealing the BottomNavigation bar in Nativescript

Currently using Nativescript 7+ and seeking to implement a feature where the TabStrip can be hidden on certain pages post navigation. Below is the relevant section of my .html code. <BottomNavigation id="bottomNav"> <TabStrip> ...

Tips for ensuring proper dependency regulations in javascript/typescript/webpack

In essence, I am in search of a method to limit dependencies, similar to how one would manage different projects (libraries) in Java or C#. Think of it as friend or internal access modifiers. I'm considering various approaches to accomplish this (suc ...

Ignore verification of unused parameters

In my typescript project compilation process, I make use of the noImplicitAny option to ensure that I specify the types for variables and arguments. However, there are instances where I have unused arguments. For instance: jQuery.ajaxTransport("+*", func ...

Simply output the integer value

Recently, I've been working on a function that I'm trying to condense into a one-liner code for a challenge on Codewars. You can find the problem here. Here's the code snippet that I currently have: export class G964 { public static dig ...

The For loop causing crashes in the Filter button functionality

I am currently working on implementing a buy it now only filter button for listings that allow that option. However, I am facing an issue where the app crashes when the button is clicked due to a for loop in my code. Strangely, if I remove the for loop, ...