【问题标题】:Typescript rxjs : is there any clean alternative to setimeout 0Typescript rxjs:settimeout 0 有什么干净的替代品吗
【发布时间】:2020-06-16 20:59:08
【问题描述】:

使用我的 Angular 应用程序,我正在使用这种处理方式

myMethod(){
 ...
 setTimeout(() => {
      this.router.navigate(['mucomponent']);
 });
}

正如我被告知的那样:setTimeout 刻不容缓 (0) 似乎要等待下一个滴答声,所有治疗都完成后才能开始我的治疗。这是近期的计划。

因为我需要这种行为

是否有任何干净的替代方法可以使用 typescriptrxjs 做得更好?

建议?

【问题讨论】:

  • 看看用装饰器制作它:netbasal.com/…。或使用 ChangeDetectorRef: angular.io/api/core/ChangeDetectorRef 如果你需要它
  • 对此挑剔:with typescript -> 它已经是 Typescript。您正在使用浏览器中的现有函数,碰巧在 TypeScript 和 JavaScript 中调用 JS 函数是相同的语法。

标签: javascript angular typescript ecmascript-6 rxjs


【解决方案1】:

可以使用Interval,也可以使用rxjs;

import { interval } from 'rxjs';
import { take} from 'rxjs/operators';

myMethod() {
  interval(0).pipe(take(1),
   ).subscribe(value =>
    this.router.navigate(['mucomponent']);
}

【讨论】:

    【解决方案2】:

    这应该可行,并且比以前的解决方案更简单:

    timer(0).subscribe(time => this.router.navigate(['mucomponent']));
    

    timer() 有 2 个参数,第二个是可选的。如果提供2个参数,第一个参数是延迟,第二个参数是周期。如果只提供一个参数,那就是延迟,定时器只会发出1个值(不会重复)。

    来自 timer() 的文档:

    如果没有指定 period(第二个参数),则输出 Observable 只发出一个 值,0。

    参考: https://rxjs-dev.firebaseapp.com/api/index/function/timer

    【讨论】:

      【解决方案3】:

      尽管接受的答案在技术上可能有效,但远非理想。 RxJS 团队正是为这个用例创建了asapScheduler

      asapScheduler.schedule(() => this.router.navigate(['mucomponent']));
      

      来自RxJS docs

      asap 调度程序将尽最大努力减少当前执行代码结束和计划任务开始之间的时间。这使它成为执行所谓的“延迟”的最佳候选者。传统上,这是通过调用 setTimeout(deferredTask, 0) 来实现的,但该技术涉及一些(尽管很小)不必要的延迟。

      【讨论】:

        【解决方案4】:

        如果你在这里尝试某种调度器,RxJS 会超时

        https://rxjs-dev.firebaseapp.com/api/operators/timeout

        【讨论】:

          猜你喜欢
          • 2020-06-20
          • 1970-01-01
          • 1970-01-01
          • 2023-03-07
          • 1970-01-01
          • 2022-11-10
          • 1970-01-01
          • 1970-01-01
          • 2023-03-08
          相关资源
          最近更新 更多