Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not bind a variable inside setInterval() in angular 6

i have used setInterval() method to show current datetime in my angular 6 project.But datatime variable value not changing after setInterval() call.its taking onload value.Here is my code

.ts

constructor(private data: DataService) {
    this.data.get_data('current-gmt-date',true)//service call
               .subscribe((data:any) => {
                  this.now = data.data.currentDateTime;//2019-01-21 20:30:0
    });
    setInterval(() => {
        this.now.setSeconds( this.now.getSeconds() + 1 );
        console.log(this.now);
        }, 1000); 
}

And .html

<span class="dateClock">Time:  {{now | date:'yyyy-MM-dd H:mm:ss ' : 'UTC' }}</span>
like image 908
Sandeep Nambiar Avatar asked Jun 17 '26 13:06

Sandeep Nambiar


1 Answers

you can use interval from rxjs

// RxJS v6+
import { interval } from 'rxjs';

//emit value in sequence every 1 second
const source = interval(1000);.
const subscribe = source.subscribe(() => console.log(new Date()));

in your case

const subscribe = source.subscribe(() => this.now = new Date()));

edit: use mergeMap for calling your observable in interval of 1 second

source.pipe(
    mergeMap(() => this.data.get_data('current-gmt-date',true))
)
.subscribe((data) => this.now = data.data.currentDateTime)
like image 126
Derviş Kayımbaşıoğlu Avatar answered Jun 19 '26 08:06

Derviş Kayımbaşıoğlu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!