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


当前回答

添加Injectable解决了我的问题:

错误代码

import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
import { HttpClient } from '@angular/common/http';

export class Chat {

修复后

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { io } from 'socket.io-client';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Chat {

其他回答

对于angular 6和更新的版本,请尝试

@Injectable({
  providedIn: 'root'
})

..就在你的服务等级上面,中间没有其他线

优势

不需要将服务添加到任何模块(将“自动发现”) 服务将是一个单例(因为它将被注入根目录)

(角文档)

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

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

当使用桶导入时,作为经验法则,首先考虑导入注射剂。

除了前面给出的答案外,当您的可注射服务缺少实际的@Injectable()装饰器时,似乎也会抛出这个错误。因此,在调试循环依赖关系以及导入/导出的顺序之前,请简单检查一下服务是否确实定义了@Injectable()。

这适用于当前Angular的最新版本——Angular 2.1.0。

我就此事发表了一期文章。

在我的例子中,将错误的参数传递给构造函数会产生这个错误,关于这个错误的基本思想是,你在不知不觉中传递了一些错误的参数给任何函数。

export class ProductComponent {
    productList: Array<Product>;

    constructor(productList:Product) { 
         // productList:Product this arg was causing error of unresolved parameters.
         this.productList = [];
    }
}

我通过去掉这个参数来解决这个问题。