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


当前回答

我在输入错误的服务名称时遇到了这个错误,即构造函数(私有myService: myService)。

对于拼写错误的服务,我能够通过检查Chrome->控制台中的页面来确定哪个服务是问题(我在构造函数中列出了几个)。您将看到作为消息的一部分的“参数”数组列表显示对象对象,对象对象,?(或者类似的事情)。请注意“?”在哪里,这是引起问题的服务的位置。

其他回答

为了搜索者的利益;我得到了这个错误。这只是一个丢失的@符号。

也就是说,这会产生无法解析MyHttpService的所有参数的错误。

Injectable()
export class MyHttpService{
}

添加缺少的@符号可以修复它。

@Injectable()
export class MyHttpService{
}

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

的地方:

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
  ) {}

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

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

在我的情况下,这是因为插件Augury,禁用它将工作得很好。替代选项是aot,也工作。

所有功劳都归功于@Boboss74,他在这里发布了答案:https://github.com/angular/angular/issues/23958

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

{
  "compilerOptions": {

     ...

    "emitDecoratorMetadata": true,

     ...

    }

}