Angular 13 + Webpack环境下依赖注入报错求助:遵循官方文档仍出现构造函数兼容问题
Let's break down this issue and walk through potential fixes—your code looks mostly correct, so the problem likely lies in a small configuration or syntax quirk that's throwing off Angular's DI system.
First, let's recap the error you're seeing:
This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid. This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator. Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors.
Potential Fix 1: Verify experimentalDecorators in tsconfig.json
You mentioned setting emitDecoratorMetadata to true, but Angular also requires experimentalDecorators to be enabled for decorators (like @Component, @Injectable) to work properly. Open your tsconfig.json and ensure both options are set in compilerOptions:
{ "compilerOptions": { // ... other options "experimentalDecorators": true, "emitDecoratorMetadata": true } }
Potential Fix 2: Replace template: require(...) with templateUrl
Using template: require('./heroes.component.html') can cause issues with Angular's metadata parsing, especially in newer versions like 13 RC. Angular expects template content to be referenced via templateUrl for external files, or inline via template with backticks. Update your HeroesComponent decorator:
@Component({ selector: 'app-heroes', templateUrl: './heroes.component.html' // Use this instead of require })
If you need inline templates, you'd write something like template:
templateUrl is the standard approach.Potential Fix 3: Clean Cache and Reinstall Dependencies
RC versions of Angular sometimes have caching issues or dependency conflicts. Try these steps:
- Delete your
node_modulesfolder - Delete
yarn.lock(since you're using Yarn) - Run
yarn cache cleanto clear Yarn's cache - Reinstall dependencies with
yarn install - Restart your dev server with
ng serve
Potential Fix 4: Double-Check HeroService and Ancestor Classes
While your HeroService looks correct (with @Injectable({ providedIn: 'root' })), make sure:
- The
Herointerface doesn't have any accidental decorators (interfaces shouldn't have Angular decorators) - The
mock-heroes.tsfile doesn't export any classes that might be interfering with DI - There are no typos in the import paths for
HeroServiceinHeroesComponent(your imports look correct, but it's worth a quick check)
Bonus: Try Upgrading to a Stable Angular 13 Version
Since you're using a release candidate (13.0.0-rc.2), there might be a known DI bug that was fixed in the stable release. Upgrading to the latest stable Angular 13 version could resolve the issue:
ng update @angular/cli @angular/core
内容的提问来源于stack exchange,提问作者Semen Shekhovtsov

