3

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
Jason
  • 33
  • 1
  • 5

1 Answers1

6

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);

OR

setInterval(()=> this.fetchDeliveries(), 5 * 60 * 1000);

If you need to pass additional parameter to fetchDeliveries

setInterval(this.fetchDeliveries.bind(this), 5 * 60 * 1000, param1, param2);

this.fetchDeliveries(param1, param2){..}
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • It works, thanks! Side question: calling startUpdate from ngOnInit doesn't work, but calling it from a component does. Any ideas? – Jason May 11 '17 at 07:03
  • 1
    @Jason ngOnInit is called for `Component` and not for a `Service` – Aleksey L. May 11 '17 at 08:28