我已经用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函数中有服务,所以它有一个提供者。而且我似乎能够将它注入到任何其他组件的构造函数中而没有任何问题。


当前回答

对我来说,这是因为我停止使用-aot标志,同时试图使编译时间更快。

 ng serve -aot

其他回答

你必须在@Component decorator中或在组件声明的模块中添加providers数组。在组件内部,你可以这样做:

@Component({
  moduleId: module.id,
  selector: 'pm-header',
  templateUrl: 'header.component.html',
  styleUrls: ['header.component.css'],
  directives: [ROUTER_DIRECTIVES, NgClass],
  providers: [MobileService]
})

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

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

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

虽然已经提到了从桶中导出类的排序,但下面的场景也可能产生相同的效果。

假设你有类A, B和C从同一个文件中导出,其中A依赖于B和C:

@Injectable()
export class A {
    /** dependencies injected */
    constructor(private b: B, private c: C) {}
}

@Injectable()
export class B {...}

@Injectable()
export class C {...}

因为Angular还不知道依赖类(比如类B和C),(可能是在运行时Angular对类A的依赖注入过程中)就会引发这个错误。

解决方案

解决方案是在执行DI的类之前声明和导出依赖类。

例如,在上面的例子中,类A是在它的依赖关系定义之后声明的:

@Injectable()
export class B {...}

@Injectable()
export class C {...}

@Injectable()
export class A {
    /** dependencies injected */
    constructor(private b: B, private c: C) {}
}

在引用接口时也会发生这种情况。

改变类的接口修复了它,使用和不使用@Inject。

对于angular 6和更新的版本,请尝试

@Injectable({
  providedIn: 'root'
})

..就在你的服务等级上面,中间没有其他线

优势

不需要将服务添加到任何模块(将“自动发现”) 服务将是一个单例(因为它将被注入根目录)

(角文档)