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


当前回答

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

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

其他回答

这个答案可能对这个问题很有帮助。此外,在我的例子中,导出默认服务是原因。

错误的:

@Inject()
export default class MobileService { ... }

正确的:

@Inject()
export class MobileService { ... }

如果服务A依赖于服务B的静态属性/方法,而服务B本身依赖于服务A的槽依赖注入,则会出现此错误。所以这是一种循环依赖,尽管它不是,因为属性/方法是静态的。可能是与AOT一起出现的错误。

在可能的情况下,错误是由升级@angular-devkit/build-angular到~0.803.*引起的。详情见https://github.com/angular/angular-cli/issues/15892。

对我来说,这是因为我的@Component装饰器和Component类之间有一个空行。这导致装饰器没有应用到类中。

除了缺少@Injectable()装饰器之外

抽象类中缺少@Injectable()装饰器会产生Can't resolve all parameters for service:(?) 装饰器需要出现在MyService和派生类BaseService中

//abstract class
@Injectable()
abstract class BaseService { ... }

//MyService    
@Injectable()
export class MyService extends BaseService {
.....
}