我已经在 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);
}
}
我在浏览器控制台中得到的错误是:
例外:无法解析 HeaderComponent 的所有参数:(?)。
我在引导函数中有服务,所以它有一个提供者。而且我似乎能够毫无问题地将它注入到我的任何其他组件的构造函数中。
原文由 Keith Otto 发布,翻译遵循 CC BY-SA 4.0 许可协议
从直接声明它的文件而不是桶中导入它。
我不知道究竟是什么导致了这个问题,但我看到它多次提到(可能是某种循环依赖)。
它也应该可以通过改变桶中出口的顺序来解决(不知道细节,但也提到过)