Mohamed Elrashid
Mohamed Elrashid

Reputation: 8599

error: "component factory found for" when using dialog.open form angluer service even though it's included in entryComponents

Proplem description

when calling dialog.open from Injectable Service it fails with Error

Error


    core.js:7187 ERROR Error: Uncaught (in promise): Error: No component factory found for LessonEndedDialogComponent. Did you add it to @NgModule.entryComponents?
    Error: No component factory found for LessonEndedDialogComponent. Did you add it to @NgModule.entryComponents?

1. Dialog Component


  @Component()
  export class LessonEndedDialogComponent {}

2. Sub Module


  @NgModule({
    declarations: [LessonEndedDialogComponent],
    entryComponents: [LessonEndedDialogComponent],
  })
  export class CoursesModule { }

3. Root Module


    @NgModule({
        declarations: [AppComponent,],
        bootstrap: [AppComponent]
    })
    export class AppModule { }

4. Root Routes


    const routes: Routes = [
      {
        path: 'courses',
        loadChildren: () => import('./courses/courses.module').then(mod => mod.CoursesModule)
      },
     ];

    @NgModule({
       imports: [RouterModule.forRoot(routes)],
       exports: [RouterModule]
    })
    export class AppRoutingModule { }

5. Injectable Service


    @Injectable({
        providedIn: 'root'
    })
    export class NavigationService {

            constructor(public dialog: MatDialog) {  }

            displayDialog() {
                this.dialog.open(LessonEndedDialogComponent);
            }
    }

Solution A

change

    providedIn: 'root'

to

    providedIn: CoursesModule

Soution A , fails

Circular dependency detected:

Cannot access 'CoursesModule' before initialization

Solution B

becase

    providedIn: 'root'

move

    entryComponents: [
            LessonEndedDialogComponent
    ],

to Root

    AppModule

Soution B , works

but LessonEndedDialogComponent is form sub Module

this will be make the root Module dependen on the sub Module

witch is bad for separation of Modules

Upvotes: 1

Views: 173

Answers (1)

Mohamed Elrashid
Mohamed Elrashid

Reputation: 8599

import Injectable Service manually

step 1

change

  @Injectable({
    providedIn: 'root'
  })

to

  @Injectable()

Step 2

use providers array on the Sub Module

    @NgModule({
        declarations: [LessonEndedDialogComponent],
        entryComponents: [LessonEndedDialogComponent],
        providers: [NavigationService],
    })
    export class CoursesModule { }

Upvotes: 1

Related Questions