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


当前回答

错误#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 { ... }

其他回答

对我来说,这是一种循环引用。 我让MyService调用Myservice2 和MyService2调用MyService。

不太好:(

我试了这里给出的几乎所有答案,但没有一个对我有帮助。

对我来说有用的是在Visual Studio Code中关闭项目,打开文件资源管理器,进入我的项目并删除dist文件夹。

然后我对所有的库进行了每个构建,然后在npm start中重新运行项目。

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

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

在我的例子中,那是我升级到主版本的TypeScript版本,以及我添加到一些Class属性中的赋值断言。

恢复更改为我解决了这个问题。(细节)

在我的情况下,添加“emitDecoratorMetadata”和“esModuleInterop”解决了这个问题。

https://github.com/thymikee/jest-preset-angular/issues/288