我已经用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:(?)的所有参数.

我在 bootstrap 功能中有服务,所以它有一个提供者.我似乎能够毫无问题地将它注入到我的任何其他组件的构造函数中.

推荐答案

从直接声明它的文件(而不是桶)导入它.

我不知道到底是什么导致了这个问题,但我看到它被多次提到(可能是某种循环依赖).

也可以通过改变桶内出口的顺序来解决(不知道细节,但也提到了)

Typescript相关问答推荐

如何使用axios在前端显示错误体

使某些类型的字段变为可选字段'

类型脚本泛型最初推断然后设置

在配置对象上映射时,类型脚本不正确地推断函数参数

异步动态生成Playwright测试,显示未找到测试

向NextAuth会话添加除名称、图像和ID之外的更多详细信息

如何按不能保证的功能过滤按键?

Express Yup显示所有字段的所有错误

TypeScrip 5.3和5.4-对`Readonly<;[...number[],字符串]>;`的测试版处理:有什么变化?

如何在Reaction路由v6.4加载器和操作中获得Auth0访问令牌?

从子类构造函数推断父类泛型类型

MatTool提示在角垫工作台中不起作用

Vue3 Uncaught SyntaxError:每当我重新加载页面时,浏览器控制台中会出现无效或意外的令牌

为什么Typescript只在调用方提供显式泛型类型参数时推断此函数的返回类型?

为什么S struct 类型化(即鸭子类型化)需要非严格类型联合?

类型脚本-在调用期间解析函数参数类型

在打字脚本中对可迭代对象进行可变压缩

如何正确地将元组表格输入到对象数组实用函数(如ZIP)中,避免在TypeScrip 5.2.2中合并所有值

Typescript泛型调用对象';s方法

如何将对象的字符串文字属性用作同一对象中的键类型