2016-05-31 47 views
1

我是AngularJS(2.0.0-beta.16)的新手。我設法通過GET請求來設置一個從API中提取數據的服務。現在,我如何設置它以每n秒來運行GET請求?我見過的其他帖子說,你可以只使用this._http.get(...).interval(5000).map(...);,但是當我已經試過了,我得到一個打字稿編譯錯誤:如何在Http Observable上使用「間隔」或類似方法?

Property 'interval' does not exist on type 'Observable'.

難道我作出愚蠢的錯誤或者是有沒有做這更好的模式?

import { Injectable } from 'angular2/core'; 
import { Http, Response } from "angular2/http"; 
import { Observable } from "rxjs/Observable"; 
import * as _ from "js/lodash.js"; 

import { Foo } from "./foo"; 

@Injectable() 
export class FooService { 
    fooList: Observable<Foo[]>; 

    constructor(private _http: Http) { 
     this.fooList = this._http.get('http://localhost:9090/api/').map(    
      response => { 
       var json = response.json(); 
       if(response.ok === true) { 
        let newFooList: Foo[] = []; 
        _.forEach(json, f => { 
         newFooList.push(new Foo(f)); 
        }); 
        return newFooList; 
       } 
      throw Error("Bad status: " + response); 
     }); 
    } 
} 
+0

使用.delay(3000)在觀察響應 – Abiodun

+0

RxJs不來的一切,它可以做出來的角2盒,你可能需要進口的'分別interval'支持。查看此頁面[這裏](http://stackoverflow.com/questions/34548924/missing-observable-methods-rxjs-5-0-0-beta-0)瞭解更多詳情。 – Ownaginatious

+0

您是否已經嘗試從「rxjs/Rx」;'而不是從'rxjs/Observable'中導入'import {Observable}? – rinukkusu

回答

1

這可能不是唯一的(或最好的)方式,但它對我有效。唯一的問題是第一個GET請求被延遲了create()指定的時間量。

import { Injectable }   from "angular2/core"; 
import { Http, Response }  from "angular2/http"; 
import { Observable }   from "rxjs/Observable"; 
import { IntervalObservable } from "rxjs/observable/IntervalObservable"; 
import * as _     from "js/lodash.js"; 

import { API_URI }   from "./constants"; 
import { Foo }    from "./foo"; 

@Injectable() 
export class FooService { 

    public fooList: Observable<Foo[]>; 

    constructor(private _http: Http) { 
     this.fooList = IntervalObservable.create(2000).flatMap(
      () => { 
       return this._http.get(API_URI); 
      }).map(
      response => { 
       var json = response.json(); 
       if(response.ok === true) { 
        let newFooList: Foo[] = []; 
        _.forEach(json, f => { 
         newFooList.push(new Foo(f)); 
        }); 
        return newFooList; 
       } 
       throw Error("Bad status: " + response); 
      }); 
    } 
} 
相關問題