You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中已注册的Service无法正常注入组件是什么原因?

问题原因
  1. 核心错误:DefaultLayoutComponent 是组件类,额外添加了仅适用于服务的 @Injectable() 装饰器,破坏了Angular对组件的依赖注入解析逻辑,导致无法正确识别DbService的提供方。
  2. 次要问题:构造函数注入的参数名与服务类名完全一致,不符合命名规范,可能干扰编译阶段的类型识别。
  3. 冗余配置:如果DbService本身已通过自身的@Injectable({providedIn: 'root'})声明为全局可用,在AppModule的providers数组重复注册属于无效冗余操作。
解决方案
  1. 删除default-layout.component.ts中@Injectable()装饰器及对应的Injectable导入语句,@Component()装饰器本身已经支持组件的依赖注入能力,无需额外声明。
  2. 调整构造函数注入的参数命名为小驼峰格式,避免与服务类名冲突。
  3. 可选优化:若DbService已配置全局提供,可删除AppModule providers数组中的DbService注册项。

修正后default-layout.component.ts代码示例

import { Component, HostBinding, OnInit } from '@angular/core';
import { DbService } from '../../db.service';
import { navItems } from './_nav';

@Component({
  selector: 'app-dashboard',
  templateUrl: './default-layout.component.html'
})
export class DefaultLayoutComponent implements OnInit {
  @HostBinding('class.c-app') cAppClass = true;

  constructor(private dbService: DbService) {}

  async ngOnInit() {
    console.log('working') 
   }
}

该问题仅出现在当前组件的原因是其他模块的组件未错误添加@Injectable()装饰器,因此可以正常解析到全局注册的DbService。

内容的提问来源于stack exchange,提问作者user68288

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 16:06:10