Angular 9:“错误:此构造函数不兼容依赖注入。”

24

在使用最新的Angular 9 CLI创建新应用程序的设置中出现了这个奇怪的错误,我不记得之前有见过。看起来可能是Ivy的一个漏洞?有什么想法如何修复将不胜感激。

从ng测试的错误结果

Error: This constructor was not compatible with Dependency Injection.
    at Module.ɵɵinvalidFactory (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:14150:1)
    at Object.Router_Factory [as factory] (http://localhost:9876/_karma_webpack_/node_modules/@angular/router/__ivy_ngcc__/fesm5/router.js:4404:67)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:787:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:792:1)
    at Object.AuthService_Factory [as factory] (ng:///AuthService/ɵfac.js:5:39)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11425:1)
    at R3Injector.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:11247:1)
    at NgModuleRef$1.push../node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js.NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/__ivy_ngcc__/fesm5/core.js:24218:1)

Error: Expected undefined to be truthy.
    at <Jasmine>
    at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/src/app/shared/components/header/header.component.spec.ts:25:23)
    at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone.js:396:1)
    at ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/node_modules/zone.js/dist/zone-testing.js:305:1)

app.component.ts

:这是一个与Angular框架相关的TypeScript文件,通常用于定义组件的行为和属性。

import { Component, HostBinding } from '@angular/core';
import { AuthService, ScreenService, AppInfoService } from './shared/services';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  @HostBinding('class') get getClass() {
    return Object.keys(this.screen.sizes)
      .filter(cl => this.screen.sizes[cl])
      .join(' ');
  }

  constructor(
    private authService: AuthService,
    private screen: ScreenService,
    public appInfo: AppInfoService,
  ) {}

  isAuthorized() {
    return this.authService.isLoggedIn;
  }
}

app.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';

import { AppComponent } from './app.component';
import { AuthService } from './shared/services';

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [AuthService, Router],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

package.json 的依赖项

  "dependencies": {
    "@angular/animations": "~9.0.2",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "~9.0.2",
    "@angular/compiler": "~9.0.2",
    "@angular/core": "~9.0.2",
    "@angular/forms": "~9.0.2",
    "@angular/platform-browser": "~9.0.2",
    "@angular/platform-browser-dynamic": "~9.0.2",
    "@angular/router": "~9.0.2",
    "devextreme": "latest",
    "devextreme-angular": "latest",
    "rxjs": "~6.5.4",
    "tslib": "^1.10.0",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.3",
    "@angular/cli": "~9.0.3",
    "@angular/compiler-cli": "~9.0.2",
    "@angular/language-service": "~9.0.2",
    "@types/jasmine": "~3.5.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "codelyzer": "^5.1.2",
    "devextreme-cli": "latest",
    "devextreme-themebuilder": "latest",
    "husky": "^4.2.3",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.3.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.0",
    "karma-jasmine": "~2.0.1",
    "karma-jasmine-html-reporter": "^1.4.2",
    "prettier": "^1.19.1",
    "pretty-quick": "^2.0.1",
    "protractor": "~5.4.3",
    "ts-node": "~8.3.0",
    "tslint": "~5.18.0",
    "tslint-config-prettier": "^1.18.0",
    "typescript": "~3.7.5",
    "webpack-bundle-analyzer": "^3.6.0"
  }

注意:修复AuthService和Router的NullInjectorError后,出现了此错误。


可能是你注入的服务中有任何一个缺少了@Injectable()。在ivy中,所有服务现在都需要有这个装饰器,无论该服务是否在其构造函数中注入了其他内容。 - Poul Kruijt
看起来不是这样。所有服务都有 @Injectable() - Andrew
5个回答

53

你在测试中将Router设置为提供程序,这不是正确的方式。

你应该在测试中导入RouterTestingModule以便能够访问它。

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [RouterTestingModule],
    declarations: [AppComponent],
    providers: [AuthService],
  }).compileComponents();
}));

我猜测在使用ivy和/或angular 9时,路由器服务的`providedIn`声明方式已经改变,因此您不能再在另一个模块中提供它(无论如何,您都不应该这样做:)){{}}

背景信息:

查看源代码,你会发现他们使用工厂以一种特殊的方式注入路由器。路由器类本身只是一个普通的类,没有@Injectable()装饰器。


1
谢谢您先生!非常感谢!考虑到它没有“服务”一词,我应该检查一下。 - Andrew

14

这个错误的另一个来源(与OP的问题无关)可能是当你有一个带有默认参数的构造函数参数时,例如:

constructor(someProp: string = 'propVal') {
    this.someProp = someProp;
}
你可以通过这种方式来解决它:
constructor(@Inject('propVal') @Optional() someProp: string) {
    this.someProp = someProp;
}

7

如果您错误地尝试注入一个接口而不是服务,也会产生此错误,哈哈。

example.interface.ts

export interface ExampleInterface {
  id: string
}

example.service.ts

import { Injectable } from '@angular/core'

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

dependent.service.ts

import { Injectable } from '@angular/core'

@Injectable({
  providedIn: 'root'
})
export class DependentService {
  constructor(
    private example: ExampleInterface // This is the error; should be ExampleService
  ) { }
}

3
如果 Angular 构建是在 --watch 模式下进行的,请尝试重新启动它。

有趣的是,当使用Angular 11.2.8时,这解决了我的问题!干杯。 - Dale
这个操作已经解决了我多年来遇到的无数奇怪问题。但是,不知何故,它总是我想尝试的最后一件事情。 - TranQ

0
在我的情况下,我有一个自定义模块,是一位开发人员在我的分支中创建的,并且它在@ngModule声明中导入Router。问题在于父模块(App)已经从Angular导入了Router,因此它重复了这个导入,导致了这个错误。
希望这能帮助其他人,只需要检查一下你的组件/模块是否正在导入/提供/声明已经在上层作用域中声明过的内容即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接