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

Angular 18组件构造函数注入服务类失败问题求助

解决Angular 18中ProductsService的注入问题

你遇到的NullInjectorError是因为服务未被注册为可注入的依赖。Angular 18默认启用独立组件模式,不再生成传统的app.module.ts,需通过以下两种方式之一完成服务注册:

方式一:根级全局注册(推荐)

在服务类上添加@Injectable装饰器并指定providedIn: 'root',服务会以单例形式在整个应用中可用:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class ProductsService
{ 
    getProducts() : string[] 
    { 
        return ["Learning Angular","Pro TypeScript","ASP.NET"]; 
    } 
}

方式二:组件级局部注册

若仅需在当前组件及其子组件范围内使用服务,可在组件的@Component装饰器中添加providers数组:

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products',
  standalone: true,
  templateUrl: './products.component.html',
  styleUrl: './products.component.css',
  imports: [CommonModule],
  providers: [ProductsService] // 新增服务注册
})
export class ProductsComponent implements OnInit {

  products: string[] = [];

  constructor(ps: ProductsService)
  { 
    this.products = ps.getProducts(); 
  }

  ngOnInit(): void
  {
  }
}

补充说明

旧教程中通过app.module.ts的providers数组注册服务的方式,仅适用于基于NgModule的传统Angular项目。Angular 18默认采用独立组件模式,因此需使用上述现代方式管理依赖注入。

内容的提问来源于stack exchange,提问作者Yossi G.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:02