Angular 10.1: "The constructor did not align with Dependency Injection."

I am facing an issue in my project where I attempted to move the spinner service out from my components. Now, I am encountering an error message that says

Error: This constructor was not compatible with Dependency Injection.
. Surprisingly, the VSCode linter is not providing any hints or warnings.

The detailed error message reads as follows:

Error: This constructor was not compatible with Dependency Injection.
    at Module.ɵɵinvalidFactory (core.js:14675)
    at Object.AppDataService_Factory [as factory] (app-data.service.ts:36)
    at R3Injector.hydrate (core.js:11289)
    at R3Injector.get (core.js:11111)
    at NgModuleRef$1.get (core.js:24243)
    at R3Injector.get (core.js:11122)
    at NgModuleRef$1.get (core.js:24243)
    at Object.get (core.js:22142)
    at getOrCreateInjectable (core.js:4079)
    at Module.ɵɵdirectiveInject (core.js:14651)

However, it seems like the app-data.service.ts:36 reference is only pointing to the end of a function. (I have highlighted it below.)

In the banner.component.ts file:

@Component({
  selector: 'app-banner-list',
  templateUrl: './banner-list.component.html',
  styleUrls: ['./banner-list.component.scss']
})
export class BannerListComponent extends BaseListComponent<BannerInterface> implements OnInit, OnDestroy {
  constructor(
    private appDataService: AppDataService<BannerInterface>,
    private helpreService: HelperService,
  ) {
    super(Banner);
  }

  // ...

  loadDatas(): Observable<any> {
    // create observable function
    const getAll$ = this.appDataService.proxy.getAll().pipe(
      map((result: any) => {
        // ...
      }),
    );

    return this.appDataService.start(getAll$, 'banner getAll');
  }
}

Regarding the app-data.service.ts file:

@Injectable({
  providedIn: 'root'
})
export class AppDataService<T extends BaseModelInterface<T>> {
  private spinner: SpinnerServiceInterface = AppModule.InjectorInstance.get(SpinnerService);
  proxy: ProxyServiceInterface<T> = new ProxyService(this.model);

  constructor(
    private model: T,
  ) { }

  start(pipeInstance: Observable<any>, spinnerName: string = 'spinner'): Observable<any> {
    return of(1).pipe(
      // switch on spinner
      tap(() => this.spinner.on(spinnerName)),

      // run observable pipe instance
      switchMap(() => pipeInstance),

      // switch off spinner
      tap(() => this.spinner.off(spinnerName)),
    );
  } // <--------- this is the 36. line
}

The ProxyService being used is part of the ddata-core package, and here is its constructor:

@Injectable()
export class ProxyService<T extends BaseModelInterface<T>> extends DataServiceAbstract<T> {
  private type: new () => T;

  constructor(
    private instance: T,
  ) {
    super(instance);
    // ...
  }

  getAll(pageNumber: number = 0): Observable<any> {
    // ...
  }
}

I am currently stuck at resolving this issue. Does anyone have any suggestions on where to find a solution for

this constructor was not compatible with Dependency Injection
? Any input would be greatly appreciated.

Answer №1

When you include

@Injectable({ providedIn: 'root' })
, Angular is instructed to generate a new instance of your AppDataService and include it in the provider list for the Root module. However, Angular lacks the ability to instantiate this object using the provided constructor, since it cannot determine how to inject a T instance for the model.

Answer №2

Ensure to avoid the same issue by always including the super() call in the inheriting class. It's crucial not to overlook this step.

@Injectable({ providedIn: 'root' })
@StoreConfig({ name: fictional })
class FictionalStore extends AppModelStore {
  // Don't forget to include this line
  constructor() {
    super();
  }
}

export abstract class AppModelStore extends Store {
  constructor() {
    // Set initial state
    super(initial);
  }
}

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

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

Limiting the image width of ngx-image-cropper to the popup container dimensions

I am currently working with a popup that contains an image cropper using ngx-image-cropper (https://www.npmjs.com/package/ngx-image-cropper) <div mat-dialog-container> <image-cropper [imageBase64]="imageFile" [mainta ...

Utilizing Typescript template strings for data inference

In coding practice, a specific convention involves denoting the child of an entity (meaning an association with another entity) with a '$' symbol. class Pet { owner$: any; } When making a reference to an entity child, users should have the opt ...

Create an object with no specified keys

I am attempting to create an empty object without specifying initial values. Here is my interface: interface MyDate { day: string; month: string; year: string; } This is my class: export class MyClass implements OnInit { date: MyDate = {}; // Err ...

After deploying on Vercel, Next.js' getServerSideProps function is returning undefined

I am trying to create a Netflix-inspired website using next.js. I am able to fetch movie data from TMDB using getServerSideProps(). While everything works as expected in development mode, once deployed on Vercel (re-deployed multiple times), the props I re ...

Tips for developing a strongly-typed generic function that works seamlessly with redux slices and their corresponding actions

Currently, I am working with @reduxjs/toolkit and aiming to develop a function that can easily create a slice with default reducers. Although my current implementation is functional, it lacks strong typing. Is there a way to design a function in such a man ...

An error has occurred in angular flex-layout: There is no exported member named ɵNgClassImpl

During my most recent Mean stack project, I utilized angular flex layout and everything ran smoothly. However, when I began a new project with angular 7 and included flex layout 8(beta), I encountered the following error: ERROR in node_modules/ ...

What is the best way to insert an image below my Bootstrap and Angular design?

I currently have the backgroundlogin.jpg image stored in the assets directory of my Angular project. I'm interested in learning how to position it below my layout, specifically in the white section indicated by the arrows in the figure provided below: ...

How to retrieve the URL of the previous page in Angular 2

My scenario involves two components: Customer and Shipment. When a user navigates from the Shipment component to the Customer component, I want the Customer component to redirect back to the Shipment component. To achieve this, I am using the following me ...

Define variables using specific class components only

Consider a scenario where we define a class as follows: class House { street: string; pools: number; helicopterLandingPlace: boolean; } Now, I have created a service to update my house. putHouse(house: House) { // some put request } How ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

Encountering an issue with Jest when using jest.spyOn() and mockReturnValueOnce causing an error

jest --passWithNoTests --silent --noStackTrace --runInBand --watch -c jest-unit-config.js Project repository An error occurred at jest.spyOn(bcrypt, 'hash').mockRejectedValue(new Error('Async error message')) Error TS2345: The argum ...

combine elements from an array into a formatted string and sort them

I'm trying to sort a string based on the length of its items This is the array const quotes = [ {ref1: 'CE255X', price_u: '1024100'}, {ref1: 'M-TK137', price_u: '65400'}, {ref1: '126A‎‎‎', ...

Issue with <BrowserRouter>: TS2769: No suitable overload for this call available

I encountered this error and have been unable to find a solution online. As a beginner in typescript, I am struggling to resolve it. The project was originally in JavaScript and is now being migrated to TypeScript using ts-migrate. I am currently fixing er ...

Generate the test output and save it to the distribution folder

When setting up my Angular 9 application in a Jenkins pipeline, I include two key steps: npm run test:prod, which translates to node --max_old_space_size=4096 ./node_modules/@angular/cli/bin/ng test --prod; and npm run build:prod, translating to node --ma ...

Utilize TypeScript's TupleIndexed type to strictly enforce read-only properties for arrays when they are used as function arguments

Looking to define a TypeScript type that accepts a type parameter T along with a tuple or ReadonlyArray of keyof T, and returns a ReadonlyArray containing the keys indexed into T. type TupleIndexed<T, K extends ReadonlyArray<keyof T>> = { [C ...

Using TypeScript with Selenium

What are the benefits of utilizing Selenium with Typescript in comparison to Selenium with Java? In what ways can Selenium+Typescript automate certain types of web applications that Selenium+Java cannot, and why is this the case? ...

Issues with the functionality of CSS Modules and hover styles_integration

After creating a react web-app with a custom build - including webpack, webpack-server, typescript, image-loaders, css, scss, and css-modules - I encountered an issue with CSS pseudo elements. The hover effect is not working as expected. .image { height ...

Properties of a child class are unable to be set from the constructor of the parent class

In my current Next.js project, I am utilizing the following code snippet and experiencing an issue where only n1 is logged: class A { // A: Model constructor(source){ Object.keys(source) .forEach(key => { if(!this[key]){ ...

Declaratively assign ambient typings to an unfamiliar object in Typescript

I am facing an issue with an external library named "gapi" that is set to a property on the window object as window.gapi. I would like to keep it there while using the @types/gapi declaration. Is there a way to achieve this, like the following code snippet ...