Angular 6-ngOnInit中的函数不会触发

时间:2019-01-16 15:42:00

标签: javascript angular angular6

我的问题是在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"}]

谢谢您的时间!

2 个答案:

答案 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`); 
  }

}