【发布时间】:2017-10-10 00:27:34
【问题描述】:
我需要每隔几分钟从服务器获取更新,所以我在 DeliveriesService 中使用了 setInterval。
这是我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 秒,只是为了确定,但不。
我在这里缺少什么? 服务在未被访问时不会“运行”吗?
(我感觉这是一个 PEBKAC 问题,我还没有完全理解 Angular。)
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
【问题讨论】:
标签: javascript angular typescript setinterval