【发布时间】:2016-10-26 03:41:50
【问题描述】:
我已经在 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 的所有参数:(?)。
我在引导函数中有服务,所以它有一个提供者。而且我似乎能够毫无问题地将它注入到我的任何其他组件的构造函数中。
【问题讨论】:
-
也许是进口?
'../'是index.ts(桶)吗?您可以尝试从直接声明它的文件中导入它吗? -
奇迹般地修复了它!奇怪的是,当我使用其他组件测试服务时,它无法使用桶。如果您想将其发布为答案而不是评论,我会接受。
-
一般是循环依赖。
-
我也遇到过循环依赖的问题。值得注意的是,较新版本的 webpack 更能告诉你这一点
-
看起来像循环依赖,如果你使用 angular >=4 这样你就可以摆脱 intex.ts (barrel) 并直接导入你需要的所有东西。
标签: angular typescript dependency-injection