【问题标题】:Can not bind a variable inside setInterval() in angular 6无法在角度 6 中绑定 setInterval() 内的变量
【发布时间】:2019-06-15 02:39:33
【问题描述】:

我已经使用 setInterval() 方法在我的 Angular 6 项目中显示当前日期时间。但是在 setInterval() 调用之后数据时间变量值没有改变。它采用 onload 值。这是我的代码

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

还有.html

<span class="dateClock">Time:  {{now | date:'yyyy-MM-dd H:mm:ss ' : 'UTC' }}</span>

【问题讨论】:

    标签: angular angular6


    【解决方案1】:

    你可以从rxjs使用interval

    // 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()));
    

    在你的情况下

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

    编辑:使用 mergeMap 以 1 秒的间隔调用您的 observable

    source.pipe(
        mergeMap(() => this.data.get_data('current-gmt-date',true))
    )
    .subscribe((data) => this.now = data.data.currentDateTime)
    

    【讨论】:

    • this.now 在我的情况下是从服务调用而不是 Date() 中获取的
    【解决方案2】:

    您需要记住您的请求是异步,因此响应需要一段时间才能到达,同时它将使用您对now 的初始值。您需要做的是在订阅块中添加您的时间间隔:

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

    记得在OnDestroy中使用clearInterval

    阅读有关异步行为的更多信息:How do I return the response from an Observable/http/async call in angular2?

    【讨论】:

      猜你喜欢
      • 2020-04-26
      • 2019-11-20
      • 1970-01-01
      • 2019-08-15
      • 2015-02-20
      • 2021-08-11
      • 2019-08-07
      • 2015-12-31
      • 1970-01-01
      相关资源
      最近更新 更多