MrLowbob MrLowbob - 21 days ago 7
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
ngOnInit
and keeps it value until
ngAfterViewInit
. However when update is called from
SetInterval
, then test is "undefined".

Thanks in advance for any help or helpful links.
:)

Answer

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

Comments