我的问题是在setStyle()
函数中,我拥有这2个数组的正确值,但不会在.map
上输入。这是为什么?如果不在setStyle()
中,应该在哪里调用.map
函数以触发ngOnInit
?
ngOnInit() {
this.existingCustomers = this.trackService.refreshExCusts()
this.nonExistingCustomers = this.trackService.refreshNonExCusts()
this.setStyle()
}
setStyle() {
// it enters here
console.log(this.existingCustomers) // has the right value
console.log(this.nonExistingCustomers) // has the right value
this.existingCustomers.map((val) => this.lineStyle.push({ // won't enter here
"customer": val.customer_name,
"color": '#000000'
}))
this.nonExistingCustomers.map((val) => this.lineStyle.push({ // won't enter here
"customer": val.customer_name,
"color": '#ff0000'
}))
console.log(this.lineStyle) // this is empty
}
数组的值:
existingCustomers = [{customer_name: "a"}, {customer_name: "b"}]
nonExistingCustomers = [{customer_name: "c"}, {customer_name: "d"}]
谢谢您的时间!
答案 0 :(得分:1)
对象数组定义不正确,代码应如下所示:
SettingsSheet
我测试了这些数组,并在控制台中将lineStyle打印为:
existingCustomers = [{ customer_name: "a" }, { customer_name: "b" }];
nonExistingCustomers = [{ customer_name: "c" }, { customer_name: "d" }];
更新:OP确认问题中的数组定义是拼写错误。因此,我唯一的另一个怀疑是[{"customer":"a","color":"#000000"},{"customer":"b","color":"#000000"},{"customer":"c","color":"#ff0000"},{"customer":"d","color":"#ff0000"}]
或map
如何使用回调函数,并因此在forEach
打印数组时出现竞争状态。尝试console.log
循环:
for
答案 1 :(得分:-1)
确保您正在实现onInit:
import { OnInit } from '@angular/core';
export class Random implements OnInit {
constructor() { }
// implement OnInit's `ngOnInit` method
ngOnInit() {
console.log(`OnInit`);
}
}