I need to fetch updates from a server every few minutes so I'm using setInterval inside my DeliveriesService.
Here is the relevant part of my 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();
}
}
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?
(I have a feeling this is a PEBKAC issue where I just don't fully understand Angular yet.)
app.module.ts
includes:
providers: [
// other services and providers
DeliveriesService,
// more providers
]
environment:
@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