【问题标题】:setInterval with time parameter based on observable variable基于可观察变量的带有时间参数的 setInterval
【发布时间】:2018-04-16 09:35:38
【问题描述】:

我无法使 setInterval 正常工作,Time 参数值基于我的 API(可观察方法)

我的服务:

getInterval(): Observable<string>{
    return this.http.get('http://my.api/dashboard/api/sysparam/refreshinterval')
    .map((res:Response) => <string> res.json().refreshInterval)   
}

这是我可观察到的获取间隔值:

this.ConnectionService.getInterval().subscribe(
                data => {
                    this.interval_2 = data;
                }
            )

如果我这样说:

this.intervalStatisticalIndicator = setInterval(() => {
                this.getDataStatisticalIndicator();
            },this.interval_2);

页面只是保持刷新,因为它忽略了 interval_2 内的值

但如果我手动将任何数字分配给变量(没有可观察的),它工作正常。

我做错了什么吗?我应该使用其他方法而不是可观察的吗? 我对 Angular 和 javascript 的东西很陌生,所以请任何帮助将不胜感激

【问题讨论】:

    标签: javascript angular typescript


    【解决方案1】:

    你只能用 observables 做到这一点。你不需要setInterval。

    import { switchMap } from 'rxjs/operators';
    import { interval } from 'rxjs/observable/interval';
    
    this.ConnectionService.getInterval()
      .pipe(switchMap(data => interval(data))
      .subscribe(() =>  this.getDataStatisticalIndicator())
    

    【讨论】:

    • 感谢您的意见。但我收到此错误:“{}”类型的参数不可分配给“数字”类型的参数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-26
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多