David Mason
David Mason

Reputation: 329

Provider in lazy loaded modules

I created a new Angular project with a lazy loaded module (LazyModuleModule).

Stackblitz: HERE

This module is lazy loaded in the routing module:

   loadChildren: () => import('../app/lazy-module/lazy-module.module').then(m => m.LazyModuleModule)

The lazy module itself has no components or any directives. It only imports another eagerly loaded module "EagerModule" with a single component (ShowComponent).

In this component I want to inject a service (TestService) that derives from an abstract Service "TestAbstractService".

I now provided the TestServiceAbstract in the EagerModule:

{provide: TestServiceAbstract, useClass: TestService}

But when compiling the project I get an errorMessage: "Can't resolve all parameters for ShowComponent".

I really do not see any reason why this approach should not work. If I provide the TestService directly in the app.module everything works, but this is strange to me.

Hint: To see the error message in stackblitz, you need to open the console and click on the "something magic happen"-text. This routes to the component with the error.

Upvotes: 1

Views: 1137

Answers (1)

The import for 'TestServiceAbstract' is not done in ShowComponent. You have imported 'TestService' instead of 'TestServiceAbstract' in ShowComponent.

Add the proper import for TestServiceAbstract which you are injecting in the constructor:

import { TestServiceAbstract } from '../../abstract.test.service';

Please replace the show.component.ts with below code. This should work:

import { Component, OnInit } from '@angular/core';
import { TestServiceAbstract } from '../../abstract.test.service';

@Component({
   selector: 'app-show',
   templateUrl: './show.component.html',
   styleUrls: ['./show.component.css']
})
export class ShowComponent implements OnInit {

   constructor(public testService: TestServiceAbstract) { }

   ngOnInit() {
     alert(this.testService.getNumber())
   }
}

Show component with alert message

Upvotes: 2

Related Questions