我已经用Angular构建了一个基本的应用程序,但是我遇到了一个奇怪的问题,我不能将服务注入到我的一个组件中。但是,它可以很好地注入我创建的其他三个组件。

对于初学者来说,这是服务:

import { Injectable } from '@angular/core';

@Injectable()
export class MobileService {
  screenWidth: number;
  screenHeight: number;

  constructor() {
    this.screenWidth = window.outerWidth;
    this.screenHeight = window.outerHeight;

    window.addEventListener("resize", this.onWindowResize.bind(this) )
  }
  
  onWindowResize(ev: Event) {
    var win = (ev.currentTarget as Window);
    this.screenWidth = win.outerWidth;
    this.screenHeight = win.outerHeight;
  }
  
}

以及它拒绝使用的组件:

import { Component, } from '@angular/core';
import { NgClass } from '@angular/common';
import { ROUTER_DIRECTIVES } from '@angular/router';

import {MobileService} from '../';

@Component({
  moduleId: module.id,
  selector: 'pm-header',
  templateUrl: 'header.component.html',
  styleUrls: ['header.component.css'],
  directives: [ROUTER_DIRECTIVES, NgClass],
})
export class HeaderComponent {
  mobileNav: boolean = false;

  constructor(public ms: MobileService) {
    console.log(ms);
  }

}

我在浏览器控制台得到的错误是这样的:

EXCEPTION:不能解析HeaderComponent:(?)的所有参数。

我在bootstrap函数中有服务,所以它有一个提供者。而且我似乎能够将它注入到任何其他组件的构造函数中而没有任何问题。


当前回答

除了前面给出的答案外,当您的可注射服务缺少实际的@Injectable()装饰器时,似乎也会抛出这个错误。因此,在调试循环依赖关系以及导入/导出的顺序之前,请简单检查一下服务是否确实定义了@Injectable()。

这适用于当前Angular的最新版本——Angular 2.1.0。

我就此事发表了一期文章。

其他回答

在我的情况下,我需要添加导入“core-js/es7/reflect”;到我的应用程序使@Injectable工作。

除了前面给出的答案外,当您的可注射服务缺少实际的@Injectable()装饰器时,似乎也会抛出这个错误。因此,在调试循环依赖关系以及导入/导出的顺序之前,请简单检查一下服务是否确实定义了@Injectable()。

这适用于当前Angular的最新版本——Angular 2.1.0。

我就此事发表了一期文章。

另一种可能是在tsconfig.json中没有将emitDecoratorMetadata设置为true

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}

如前所述,这个问题是由桶内的导出排序引起的,而桶内的导出排序是由循环依赖关系引起的。

更详细的解释在这里:https://stackoverflow.com/a/37907696/893630

在我的例子中,我从同一个组件文件中导出了一个类和一个Enum:

mComponent.component.ts:

export class MyComponentClass{...}
export enum MyEnum{...}

然后,我试图从MyComponentClass的子类中使用MyEnum。这导致了“不能解决所有参数”错误。

通过将MyEnum从MyComponentClass移动到一个单独的文件夹中,这解决了我的问题!

正如Günter Zöchbauer提到的,这是因为服务或组件是循环依赖的。