【问题标题】:Angular 6 run a function in every X secondsAngular 6 每 X 秒运行一个函数
【发布时间】:2019-03-11 07:10:11
【问题描述】:

我有一个函数叫

opensnack(text) { ... };

使用给定的文本输入打开一个angular material snackbar

我想要做的是每隔 10 秒调用一次这个函数。

我应该怎么做?

【问题讨论】:

标签: angular typescript angular6


【解决方案1】:

使用来自rxjsinterval

方法如下:

import { interval, Subscription } from 'rxjs';

subscription: Subscription;

...

//emit value in sequence every 10 second
const source = interval(10000);
const text = 'Your Text Here';
this.subscription = source.subscribe(val => this.opensnack(text));

...

ngOnDestroy() {
  this.subscription.unsubscribe();
}

或者,您可以使用 setInterval 作为 Window 对象上的方法。所以你不需要导入任何东西来使用它。

intervalId = setInterval(this.opensnack(text), 10000);

...

ngOnDestroy() {
  clearInterval(this.intervalId);
}

这里有一个SAMPLE STACKBLITZ 供您参考。

【讨论】:

  • 我需要导入一些东西才能使用 SetTimeout 吗?因为它给了我一些这样的错误
  • 我的错,这是一个错字。我的意思是setInterval 因为它可以作为 Window 对象上的 API 使用,所以你不需要导入任何东西来使用它。
  • 也许我隐瞒了什么,但似乎没有用。可以请教一下吗? stackblitz.com/edit/angular-enzk8t
  • 刚刚为您的参考添加了一个示例 Stackbliz。请看看它,让我知道这是否适合你。请务必仔细阅读 cmets :)
  • @hellmit100,如果您将回调参数设置为箭头函数,它将起作用。 () => this.addNum() stackblitz.com/edit/angular-bgb963?file=src/app/…
【解决方案2】:

您可以利用rxjs 库每 X 秒运行一次函数。

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

...

 interval(1000)
    .pipe(takeWhile(() => !stop))
    .subscribe(() => {
      // place you code here
    });

上面的代码sn-p会每1秒执行一次订阅的语句,直到stop条件设置为真。

【讨论】:

  • 从'rxjs'导入{间隔};从 'rxjs/operators' 导入 { takeWhile };构造函数() { this.createNewFutureCostingSNotifier(); } 公共 createNewFutureCostingSNotifier() { console.log('createNewFutureCostingSNotifier()'); interval(1) .pipe(takeWhile(() => false)) .subscribe(() => { console.log('createNewFutureCostingSNotifier() 正在工作!'); });但不工作。
  • @RejwanulReja 您已将停止条件直接设置为 false
【解决方案3】:

尝试使用setInterval

setInterval 将允许定期运行函数,运行之间的间隔

https://javascript.info/settimeout-setinterval

示例:

function opensnack(text: string) : void {
  console.log(text);
}

setInterval(opensnack, 10000, "my text"); <-- run every 10 second

你可以看看这个stackblitz example

【讨论】:

    【解决方案4】:

    Angular 6 每 X 秒运行一次函数

    import { Component, OnInit } from '@angular/core';
    import { Observable } from 'rxjs';
    
    @Component({
        selector: 'my-app',
        template: `<h2>
          Now {{time | date: 'hh:mm:ss'}}
          
          <hr /> 
          Now {{time$ | async | date: 'hh:mm:ss'}}
        </h2>`
    })
    export class AppComponent {
      time: Date;
      time$;
    
      constructor() {
        // First way: manual subscribe
        Observable
          .interval(1000)
          .map(() => new Date())
          .subscribe(res => this.time = res)
    
        // Angular way: by using the `async` pipe
        this.time$ = Observable.interval(1000).map(() => new Date())
      }
    }
    

    【讨论】:

      【解决方案5】:
      export class AComponent implements OnInit {
        id: string = "1";
        mySub: Subscription;
      
        constructor(private http: HttpClient) {
          this.mySub = interval(8000).subscribe((func => {
            this.onIdSelect(this.id);
          }))
        }    
        ngOnInit(): void {
        }
        onIdSelect(id) {
          this.http.post('https://jsonplaceholder.typicode.com/posts', id).subscribe((res => {
            console.log(res);
          }))
          // this.mySub.unsubscribe(); 
        }
      }
      

      rxjs 导入时间间隔和订阅。 在这里,代码每8seconds 调用一次onIdSelect() 方法。因此,每个8seconds 之后都会在控制台上打印发布响应。如果您只想在8seconds 之后调用该方法一次,则只需取消订阅mySub 变量即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-04
        • 2018-11-08
        • 2020-06-09
        • 2014-03-05
        • 1970-01-01
        • 1970-01-01
        • 2017-07-07
        • 2012-01-09
        相关资源
        最近更新 更多