2017-05-11 12 views
1

私はDeliveriesService内でsetIntervalを使用しているので、数分おきにサーバーから更新を取得する必要があります。コンポーネントがサービスをインポートし、deliveries$にアクセスするようAngularサービスのsetIntervalはなぜ1回だけ起動しますか?

はこことすぐに私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(); 
    } 
} 

最初の間隔火災の関連する部分です。 コンソールでサーバーデータと「更新配信」を取得しましたが、それだけです。 私は30秒にも間隔を持ってきました。

私はここで何が欠けていますか? サービスはアクセスされていないときに「実行」されませんか?

(私はこれは私がまだ完全にはアンギュラ理解していないPEBKACの問題で感じている。)

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 

答えて

3

をあなたが関数の戻り値を渡す代わりに実行される関数参照を渡す必要があり、.bind()を使用してコンテキストを設定する

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

OR

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

あなたはfetchDeliveries

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

this.fetchDeliveries(param1, param2){..} 
+2

や '()=> this.fetchDeliveries()' –

+0

DOHに追加のパラメータを渡す必要がある場合は!それは完璧な意味を持っている...今すぐテスト – Jason

+0

それは、ありがとう! サイド質問:ngOnInitからのstartUpdateの呼び出しは機能しませんが、コンポーネントから呼び出すことはできません。 アイデア – Jason

関連する問題