3

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>
Joël
  • 2,723
  • 18
  • 36
Sandeep Nambiar
  • 1,656
  • 3
  • 22
  • 38

2 Answers2

1

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)
Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
0

You need to remember your request is asynchronous, so it takes a while for the response to arrive, in meanwhile, it will use the initial value you have for now. What you need to do is to add your interval inside the subscribe block:

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); 
    });
}

Remember to use clearInterval in OnDestroy.

Read more about ansynchronous behavior: How do I return the response from an Observable/http/async call in angular2?

AT82
  • 71,416
  • 24
  • 140
  • 167