MrLowbob MrLowbob - 1 year ago 124
Javascript Question

Angular2 resets variable to undefined?

I am relatively new to angular2 and just finished the tutorial and tour of heroes stuff, from their website and now try to do some stuff with angular and amChart.

Currently i have some trouble with variables that don't keep their assigned value and I don't know, what the problem is - even without amcharts and just using some number type variables for testing, the problem occurs and I think I miss something, im not aware of...

So this is my class:

export class SomeComponent {
chart: AmCharts.AmChart;
test: number;

constructor() {}

ngOnInit(): void {
this.test = 5;
console.log("number: " + this.test);

ngAfterViewInit(): void {
console.log("number2: " + this.test);
this.chart = AmCharts.makeChart([...]);
setInterval(this.update, 5000);
console.log("number3: " + this.test);

update(): void {
console.log("number in update:" + this.test);

and this is my output:

number: 5
number2: 5
number3: 5
number in update: 5
number in update: undefined

So obviously, test is initialized with the value 5 in
and keeps it value until
. However when update is called from
, then test is "undefined".

Thanks in advance for any help or helpful links.

Answer Source

Passing method or function references this way "breaks" this.

setInterval(this.update, 5000);

Use .bind()

setInterval(this.update.bind(this), 5000);

or arrow functions

setInterval(() => this.update(), 5000);

to fix the problem

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download