Angular 8升级至10后出现ModalDialogService无提供者错误求助
Hey there, let's dig into this frustrating provider error you're hitting post-upgrade. I've gone over your setup and the steps you've already tried, so here are some targeted fixes to test out:
1. Fix ngx-modal-dialog Version Compatibility
Your package.json uses ngx-modal-dialog@3.0.0, but this version was built for Angular 9. Angular 10 introduced breaking changes to the R3Injector that this older release doesn't account for. Upgrade to the first version explicitly supporting Angular 10:
npm install ngx-modal-dialog@3.1.0 --save
2. Double-Check Module Import Setup
Even if you added ModalDialogModule.forRoot() in AppModule, make sure:
- You haven't imported
ModalDialogModule(without.forRoot()) in any lazy-loaded feature modules—this can break root-level provider configuration. - The import is placed before feature modules in your AppModule's
importsarray. - There are no typos in the import statement:
import { ModalDialogModule } from 'ngx-modal-dialog'; @NgModule({ imports: [ // ... other core modules ModalDialogModule.forRoot() ], // ... }) export class AppModule { }
3. Correct Manual Provider Registration
If you're manually adding the service to providers, ensure you're using the exact class from ngx-modal-dialog (avoid accidental conflicts with similarly named services from other libraries):
import { ModalDialogService } from 'ngx-modal-dialog'; @NgModule({ providers: [ // ... other providers ModalDialogService ], // ... }) export class AppModule { }
Skip useClass unless you're intentionally overriding the service—adding the class directly is sufficient for standard use cases.
4. Clean Dependencies and Reinstall
Corrupted node_modules or cached packages often cause injection issues. Try these steps:
- Delete your
node_modulesfolder:rm -rf node_modules(Windows:rd /s /q node_modules) - Clear npm cache:
npm cache clean --force - Reinstall dependencies:
npm install - Restart your dev server with AOT compilation (it catches more injection bugs):
ng serve --aot
5. Explicitly Specify the Service Token (If Conflicts Exist)
If another library in your dependencies happens to provide a service named ModalDialogService, use @Inject() to clarify which one you need in your components:
import { Component, Inject } from '@angular/core'; import { ModalDialogService } from 'ngx-modal-dialog'; @Component({ // ... component config }) export class YourComponent { constructor(@Inject(ModalDialogService) private modalService: ModalDialogService) { } }
6. Update Zone.js to Match Angular 10
Your current zone.js@0.10.3 is compatible, but updating to the latest patch version can eliminate zone-related injection quirks:
npm install zone.js@~0.10.3 --save
内容的提问来源于stack exchange,提问作者Krzysztof

