尝试将服务注入角度组件时出错“ EXCEPTION:无法解析组件的所有参数”,为什么? [英] Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?
问题描述
我已经在Angular中构建了一个基本应用程序,但是遇到了一个奇怪的问题,即我无法将服务注入我的组件之一。
I've built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three other components I have created, however.
对于初学者来说,这是一项服务:
For starters, this is the service:
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);
}
}
我在浏览器控制台中看到的错误是:
The error I get in the browser console is this:
例外:无法解析HeaderComponent的所有参数:(?)。
EXCEPTION: Can't resolve all parameters for HeaderComponent: (?).
我在引导功能中有该服务,因此它具有提供程序。而且我似乎可以将其注入到其他任何组件的构造函数中。
I have the service in the bootstrap function so it has a provider. And I seem to be able to inject it into the constructor of any of my other components without issue.
推荐答案
我也遇到了这个问题通过将服务A注入服务B中,反之亦然。
I also encountered this by injecting service A into service B and vice versa.
我认为这很快就失败了是一件好事,因为无论如何应该避免使用 。如果您希望服务更具模块化和可重用性,则最好避免使用循环引用。这篇帖子突出显示了周围的陷阱。
I think it's a good thing that this fails fast as it should probably be avoided anyway. If you want your services to be more modular and re-usable, it's best to avoid circular references as much as possible. This post highlights the pitfalls surrounding that.
因此,我有以下建议:
- 如果您感觉上课了互动太频繁(我在谈论功能嫉妒),您可能需要考虑将2种服务合并为1类。
- 如果上述不适用于您,请考虑使用第三项服务(
EventService
),这两种服务都可以注入该第三项服务来交换消息。
- If you feel the classes are interacting too often (I'm talking about feature envy), you might want to consider merging the 2 services into 1 class.
- If the above doesn't work for you, consider using a 3rd service, (an
EventService
) which both services can inject in order to exchange messages.
这篇关于尝试将服务注入角度组件时出错“ EXCEPTION:无法解析组件的所有参数”,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!