Angular中数组已赋值仍提示未初始化错误如何解决?
问题原因
TypeScript 是静态类型语言,要求类的所有属性必须先在类的作用域内显式声明,才能通过 this 访问对应属性。你只是在 ngOnInit 生命周期方法中给 this.sales 赋值,相当于动态给类实例添加属性,并没有提前告知 TypeScript 该类存在 sales 属性,因此类型检查阶段就会抛出该错误,和你有没有赋值没有关系。
解决方法
在 AppComponent 类的属性声明区域提前声明 sales 属性即可,推荐先定义数组项的类型约束,写法如下:
import { Component } from '@angular/core'; // 先定义sales数组每一项的类型 interface SalesItem { brand: string; lastYearSale: string; thisYearSale: string; lastYearProfit: string; thisYearProfit: string; } @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'excel'; // 显式声明sales属性,指定类型并初始化空数组 sales: SalesItem[] = []; ngOnInit() { this.sales = [ { brand: 'Apple', lastYearSale: '51%', thisYearSale: '40%', lastYearProfit: '$54,406.00', thisYearProfit: '$43,342' }, { brand: 'Samsung', lastYearSale: '83%', thisYearSale: '96%', lastYearProfit: '$423,132', thisYearProfit: '$312,122' }, { brand: 'Microsoft', lastYearSale: '38%', thisYearSale: '5%', lastYearProfit: '$12,321', thisYearProfit: '$8,500' }, { brand: 'Philips', lastYearSale: '49%', thisYearSale: '22%', lastYearProfit: '$745,232', thisYearProfit: '$650,323,' }, { brand: 'Song', lastYearSale: '17%', thisYearSale: '79%', lastYearProfit: '$643,242', thisYearProfit: '500,332' }, { brand: 'LG', lastYearSale: '52%', thisYearSale: ' 65%', lastYearProfit: '$421,132', thisYearProfit: '$150,005' }, { brand: 'Sharp', lastYearSale: '82%', thisYearSale: '12%', lastYearProfit: '$131,211', thisYearProfit: '$100,214' }, { brand: 'Panasonic', lastYearSale: '44%', thisYearSale: '45%', lastYearProfit: '$66,442', thisYearProfit: '$53,322' }, { brand: 'HTC', lastYearSale: '90%', thisYearSale: '56%', lastYearProfit: '$765,442', thisYearProfit: '$296,232' }, { brand: 'Toshiba', lastYearSale: '75%', thisYearSale: '54%', lastYearProfit: '$21,212', thisYearProfit: '$12,533' } ]; } }
如果暂时不需要严格的类型约束,也可以简化声明为 sales: any[] = [],不推荐长期使用该写法。
内容的提问来源于stack exchange,提问作者Niall
相关产品推荐
相关产品推荐

