我如何在Http Observable上使用“Interval”或类似的东西?

时间:2016-05-31 23:36:51

标签: angularjs http typescript angular rxjs

我是AngularJS(2.0.0-beta.16)的新手。我设法通过GET请求设置从API中提取数据的服务。现在,如何将其设置为每 n 秒运行GET请求?我已经看到其他帖子说你可以使用this._http.get(...).interval(5000).map(...);,但是当我尝试过时,我收到了一个Typescript编译错误:

  

'Observable'类型中不存在属性'interval'。

我犯了一个愚蠢的错误,还是有更好的模式来做这件事?

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

1 个答案:

答案 0 :(得分:1)

这可能不是唯一(或最好的)方式,但它对我有用。唯一的问题是第一个GET请求延迟了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); }); } } 指定的时间量。

{{1}}