Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 View not updated when using setInterval

Tags:

angular

I am using Angular2 RC5 - and I have a strange problem. In my main component I use for testing purposes in my constructor:

 setInterval(() => {
        this.test = new Date().getMilliseconds().toString();           
    }, 500);

Binding in my template is

<p>{{test}}</p>

Upon loading or reloading the page it either displays a value (but does not change on further ticks), somtimes it works as intended (updates value on every tick), and sometimes just displays the initial value and does not change at all. Seems random.

I get crazy over this, as it seems in the official plunker version it works without a problem. (Edit: Plunker link )

I get the same behaviour when using this code in other components aswell..

Anyone any idea?

like image 470
Mr. Muh Avatar asked Aug 20 '16 18:08

Mr. Muh


1 Answers

Use this, This worked fine for me.

import { Observable } from 'rxjs/Observable';

Observable.interval(500)
    .subscribe(() => {
    this.test = new Date().getMilliseconds().toString();    
})
like image 67
Sangwin Gawande Avatar answered Nov 12 '22 18:11

Sangwin Gawande