Why is setInterval in an Angular service only firing one time?

我只是一个虾纸丫 提交于 2019-12-11 08:20:00

问题


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

回答1:


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){..}


来源:https://stackoverflow.com/questions/43908009/why-is-setinterval-in-an-angular-service-only-firing-one-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!