【发布时间】:2018-12-31 23:08:22
【问题描述】:
我对学习 Angular 还是很陌生,我还没有完全理解所有内容,所以请多多包涵。我创建了一个对象数组,其中包含我需要的所有数据,并尝试使用 ngFor 指令显示数据。我知道数据在那里,因为我通过控制台将其注销,但我不知道如何使用我的 ngFor 循环访问数据。
这是控制台记录的数据,console.log(this.forecastData);
[HighLows]
0: HighLows {days: Array(6), highs: Array(6), lows: Array(6)}
length: 1
__proto__: Array(0)
这是我的html
<div *ngFor="let data of this.weather.forecastHiLoData">
{{data.days}}
{{data.highs}}
{{data.lows}}
</div>
我尝试了不同的场景,但只会给我类似的错误
<div *ngFor="let data of this.weather.forecastHiLoData[0]">
或
{{data[0].days}}
也许这就是我构造新对象的方式。当我控制台将 HighLows 数组注销到第零个索引 console.log(this.forecastData[0]) 时,我得到了这个
HighLows {days: Array(6), highs: Array(6), lows: Array(6)}
days: (6) [1546225200000, 1546236000000, 1546322400000, 1546408800000, 1546495200000, 1546581600000]
highs: (6) [4.56, 13.95, 2.75, -0.24, 9.14, 13.93]
lows: (6) [4.56, 3.73, -1.44, -6.73, -8.73, -5.08]
__proto__: Object
https://stackblitz.com/edit/angular-wtu3ym?file=src%2Fapp%2Fapp.component.html
更新
看起来我的终端出现了错误,我必须查看直到现在才意识到的错误。我仍在学习如何使用类/接口和构造函数。
ERROR in src/app/services/weather.service.ts(39,5): error TS2322: Type 'any[]' is not assignable to type 'HighLows'.
Property 'days' is missing in type 'any[]'.
src/app/services/weather.service.ts(40,20): error TS2345: Argument of type 'Days[]' is not assignable to parameter of type 'number[]'.
Type 'Days' is not assignable to type 'number'.
src/app/services/weather.service.ts(150,32): error TS2345: Argument of type 'number' is not assignable to parameter of type 'Days'.
【问题讨论】:
-
只需在您分配数组值的位置添加代码 - 从您的 html 中删除
this关键字并尝试访问可能解决您的解决方案的数组 -
@rahul 我有 this 这个词的原因是因为正在我的服务组件中访问数据。
-
是的,但我认为这不适用于您的 html 和组件装饰器,如果您将 html 添加为
templateUrl,那么该 html 将成为您组件的一部分 - 所以html 将访问所有属性,而无需使用 this -
@rahul 哦,好吧。你是对的。我删除了所有 this 关键字,我页面上的所有其他内容仍然正常工作。我没有意识到您在访问依赖注入器时不必指定 this。但是,我的数据仍然没有被迭代
-
请使用stackblitz.com。并在上面设置你的测试项目,以便轻松查看。
标签: angular typescript