Angular 6每X秒运行一次功能

时间:2018-10-05 18:24:42

标签: angular typescript angular6

我有一个名为

的函数

opensnack(text) { ... };

正在使用给定的文本输入来打开angular material snackbar

我想做的是每10秒调用一次此函数。

我应该怎么做?

5 个答案:

答案 0 :(得分:5)

您可以使用rxjs库每隔X秒运行一个函数。

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

...

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

以上代码段将每1秒执行一次订阅的语句,直到stop条件设置为true。

答案 1 :(得分:4)

使用rxjs

中的 interval

方法如下:

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

答案 2 :(得分:1)

尝试使用setInterval

setInterval将允许在运行之间的间隔内定期运行功能

https://javascript.info/settimeout-setinterval

示例:

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

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

您可以查看此stackblitz example

答案 3 :(得分:0)

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导入间隔和订阅。 在这里,代码每个onIdSelect()都调用8seconds方法。因此,每隔8seconds之后,后响应将被打印在控制台上。如果您只想在8seconds之后调用一次该方法,则只需取消订阅mySub变量即可。

答案 4 :(得分:0)

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