Sandeep Nambiar
Sandeep Nambiar

Reputation: 1676

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>

Upvotes: 3

Views: 1450

Answers (2)

AVJT82
AVJT82

Reputation: 73377

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?

Upvotes: 0

Derviş Kayımbaşıoğlu
Derviş Kayımbaşıoğlu

Reputation: 30665

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)

Upvotes: 1

Related Questions