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


当前回答

在我的例子中,我错过了调用我继承的类的构造函数。

之前:

@Component({ ... })
export class ComponentA extends ComponentParent {
  // ...
}

后:

@Component({ ... })
export class ComponentA extends ComponentParent {
  constructor(protected route: ActivatedRoute, protected store$: Store<AppState>) {
    super(route, store$);
  }
  // ...
}

其他回答

就我而言,原因如下:

我的可注入服务A扩展了另一类B B有一个需要参数的构造函数 我没有在A中定义任何构造函数

因此,在尝试创建对象a时,默认构造函数失败了。我不知道为什么这不是一个编译错误。

我通过在a中添加一个构造函数来解决这个问题,它正确地调用了B的构造函数。

添加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 {

问题是,模块中的元素应该对属于同一模块的元素使用相对导入;它们永远不应该通过模块的公共API桶(或一般的桶)导入。

该导入的问题是,如果依赖于服务的某些东西首先在桶中加载(直接或不直接),那么DI系统将失败,因为服务还没有声明,因此无法解决。

尝试从absolute更改import:

import { UserService } from 'src/app/users/user.service';

相对:

import { UserService } from '../../users/user.service';

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

不太好:(

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

@Injectable({
  providedIn: 'root'
})

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

优势

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

(角文档)