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


当前回答

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

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

其他回答

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

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

从直接声明它的文件中导入,而不是从桶中导入。

我不知道是什么导致了这个问题,但我看到它被提到过几次(可能是某种循环依赖)。

它也应该可以通过改变桶中的出口顺序来修复(不知道细节,但也提到了)

错误#1:忘记装饰:

//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
export class MyFooService { ... }

错误2:省略“@”符号:

//Uncaught Error: Can't resolve all parameters for MyFooService: (?).
Injectable()
export class MyFooService { ... }

错误#3:省略“()”符号:

//Uncaught Error: Can't resolve all parameters for TypeDecorator: (?).
@Injectable
export class MyFooService { ... }

错误4:小写的“i”:

//Uncaught ReferenceError: injectable is not defined
@injectable
export class MyFooService { ... }

错误5:你忘了: import {Injectable} from @angular/core;

//Uncaught ReferenceError: Injectable is not defined
@Injectable
export class MyFooService { ... }

正确的:

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

如果你试图注入一个接口,也会发生这个错误:

的地方:

export const MY_SERVICE = new InjectionToken<MyService>('MY_SERVICE');

export interface MyService {
  // ...
}

@Injectable()
export class MyServiceImpl implements MyService {
  // ...
}

不正确的:

  constructor(
    private myService: MyService
  ) {}

正确的:

  constructor(
    @Inject(MY_SERVICE) private myService: MyService
  ) {}

对我来说,这个问题甚至更烦人,我正在使用服务中的服务,忘记在appModule中添加它作为依赖项! 希望这能帮助一些人节省几个小时的应用程序分解,只是重新建立它