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
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);
}
<span class="dateClock">Time: {{now | date:'yyyy-MM-dd H:mm:ss ' : 'UTC' }}</span>
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With