为什么 Angular 服务中的 setInterval 只触发一次? [英] Why is setInterval in an Angular service only firing one time?
问题描述
我需要每隔几分钟从服务器获取更新,因此我在 DeliveriesService 中使用了 setInterval.
I need to fetch updates from a server every few minutes so I'm using setInterval inside my DeliveriesService.
这是我的deliveries.service.ts
import { Injectable, OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';
import { Http } from '@angular/http';
import { Delivery, Product } from './delivery';
@Injectable()
export class DeliveriesService implements OnInit {
private fetchUrl = 'https://my.url';
private getInt;
public deliveries$ = new Subject<Array<Delivery>>();
constructor(private http: Http) { }
ngOnInit() {
this.startUpdate();
}
startUpdate(): void {
console.log('starting delivery fetch');
this.getInt = setInterval(this.fetchDeliveries(), 5 * 60 * 1000);
}
stopUpdate(): void {
clearInterval(this.getInt);
}
updateNow(): void {
this.stopUpdate();
this.startUpdate();
}
fetchDeliveries(): void {
console.log('updating deliveries');
this.http.get(this.fetchUrl)
.map(res => {
// do stuff, process data, etc.
}).subscribe();
}
}
当组件导入服务并访问 deliveries$
时,第一个间隔会立即触发.我在控制台中获得了服务器数据和更新交付"一次,但仅此而已.我什至把时间间隔缩短到 30 秒,只是为了确保,不是.
The first interval fires as soon as a component imports the service and accesses deliveries$
.
I get the server data and "updating deliveries" in the console once, but that's it.
I even brought the interval down to 30 seconds, just to make sure, and nope.
我在这里错过了什么?服务不被访问时是否运行"?
What am I missing here? Does the service not "run" when it's not being accessed?
(我感觉这是一个 PEBKAC 问题,我还没有完全理解 Angular.)
(I have a feeling this is a PEBKAC issue where I just don't fully understand Angular yet.)
app.module.ts
包括:
providers: [
// other services and providers
DeliveriesService,
// more providers
]
环境:
@angular/cli: 1.0.1
node: 7.8.0
os: darwin x64
@angular/cli: 1.0.1
@angular/common: 4.1.1
@angular/compiler: 4.1.1
@angular/compiler-cli: 4.1.1
@angular/core: 4.1.1
@angular/forms: 4.1.1
@angular/http: 4.1.1
@angular/platform-browser: 4.1.1
@angular/platform-browser-dynamic: 4.1.1
@angular/router: 4.1.1
推荐答案
需要传递要执行的函数引用而不是传递函数的返回值并使用 .bind()
设置上下文
You need to pass the function reference to be executed instead of passing the return value of the function and use .bind()
to set context
setInterval(this.fetchDeliveries.bind(this), 5 * 60 * 1000);
或
setInterval(()=> this.fetchDeliveries(), 5 * 60 * 1000);
如果您需要将附加参数传递给 fetchDeliveries
If you need to pass additional parameter to fetchDeliveries
setInterval(this.fetchDeliveries.bind(this), 5 * 60 * 1000, param1, param2);
this.fetchDeliveries(param1, param2){..}
这篇关于为什么 Angular 服务中的 setInterval 只触发一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!