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

Angular 4创建含对象数组的对象报错问题求助

Angular 4报错:NullInjectorError: No provider for Array! 解决方案

嘿,我一眼就看出问题所在了!你遇到的NullInjectorError: No provider for Array!错误,根源是错误地把组件的属性初始化写成了构造函数的依赖注入参数。

问题分析

Angular的组件构造函数参数是用来做依赖注入的——它会自动尝试从注入器中获取对应类型的实例。你在HistoricoAComponent的构造函数里写了constructor(historico: HistoricoData[]) { ... },Angular会认为你要注入一个HistoricoData[]类型的依赖,但这种数组类型并没有注册对应的提供者,所以就抛出了这个错误。

而你的模型类DisciplinaStatus和HistoricoData的定义是完全没问题的,不需要修改。

修复后的组件代码

把构造函数的参数去掉,换成在组件类内部声明属性并初始化:

import { Component, OnInit } from '@angular/core';
import { DisciplinaStatus } from './models/disciplinaStatus.model';
import { HistoricoData } from './models/historicoData.model';

@Component({
  selector: 'historico-a-component',
  templateUrl: './historico-a.component.html',
  styleUrls: ['./historico-a.component.css']
})
export class HistoricoAComponent implements OnInit {
  // 1. 在组件类中声明属性
  historico: HistoricoData[];

  constructor() {
    // 2. 在构造函数内部初始化属性(静态数据适合在这里处理)
    this.historico = [
      new HistoricoData('2016/1', [
        new DisciplinaStatus('001','Redes 1','Completo','Everthon Valadão','60',71.5),
        new DisciplinaStatus('002','Compiladores','Completo','Walace','60',45.5)
      ]),
      new HistoricoData('2016/2', [
        new DisciplinaStatus('001','AED','Completo','Diego Melo','60',22.5),
        new DisciplinaStatus('002','Teoria','Completo','Diego Melo','60',89.5)
      ])
    ];
  }

  ngOnInit(): void {
    // 如果是异步获取的数据(比如从API请求),建议在这里初始化属性
  }
}

关键修改点

  • 移除了构造函数中的historico: HistoricoData[]参数,避免触发Angular的依赖注入逻辑
  • 在组件类中显式声明historico属性,然后通过this.historico赋值初始化

这样修改后,你的代码就能正常运行了,组件可以正确创建包含对象数组的对象结构。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:48:58