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


当前回答

如前所述,这个问题是由桶内的导出排序引起的,而桶内的导出排序是由循环依赖关系引起的。

更详细的解释在这里:https://stackoverflow.com/a/37907696/893630

其他回答

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

export class ProductComponent {
    productList: Array<Product>;

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

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

在我的情况下,修复是替换相对路径与绝对 之前

import {Service} from './service';

import {Service} from 'src/app/services/service';

看起来是typescript/angular的问题

您可以重试执行如下命令:

发球——开球

在引用接口时也会发生这种情况。

改变类的接口修复了它,使用和不使用@Inject。

明白了!

如果以上答案都对您没有帮助,那么您可能正在从组件注入服务的同一个文件中导入某个元素。

我解释得更好:

这是服务文件:

// your-service-file.ts
import { helloWorld } from 'your-component-file.ts'

@Injectable()
export class CustomService() {
  helloWorld()
}

这是组件文件:

@Component({..})
export class CustomComponent {
  constructor(service: CustomService) { }
}

export function helloWorld() {
  console.log('hello world');
}

因此,即使符号不在同一个组件中,而只是在同一个文件中,也会引起问题。将符号(可以是函数、常量、类等等)移动到其他地方,错误就会消失