开始首次呼叫IntervalObservable瞬间 [英] Start first call of IntervalObservable instant

查看:174
本文介绍了开始首次呼叫IntervalObservable瞬间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用IntervalObservable连续调用应用程序的服务器端.我可以订阅和取消订阅Oberservable,并且一切正常,但有一个例外:

I'm using an IntervalObservable to make continuous calls to the server side of my application. I can subscribe and unsubscribe to to the Oberservable and everything works fine with one exception:

对服务器的第一次呼叫被延迟,但是我希望它是即时的. IntervalObservable的行为原则上是正确的,但不符合我的要求.

The first call to the server is delayed, but I want it to be instant. The behaviour of the IntervalObservable is in principle correct, but does not match my requirements.

@Injectable()
export class LoggerService {
  constructor(private http: Http) { }
  private apiURL = 'assets/file.json'; 

  getList() {
       return IntervalObservable.create(1000).flatMap(() 
       => this.http.get(this.apiURL))
      .map(this.extractData)
      .catch(this.handleError);
  }
  private extractData(res: Response) {
    var fooot = new Foo();
    fooot.fillFromJSON(JSON.stringify(res.json()));
    return fooot;
  }

  private handleError(error: any) {
    let errMsg = (error.message) ? error.message :
      error.status ? `${error.status} - ${error.statusText}` : 'Server error';
    console.error(errMsg);
    return IntervalObservable.throw(errMsg);
  }
}

那么我如何在首次调用后立即以定义的延迟调用服务器?

So how can I call the server instant on the first call and afterwards with the defined delay?

推荐答案

两件事,

  1. 您可以使用工厂方法代替派生类型,即使用Observable.interval(3000)代替IntervalObservable.create
  2. 您可以使用timer来代替一个运算符:

  1. You can use the factory methods instead of the derived types, i.e. Observable.interval(3000) instead of IntervalObservable.create
  2. You can use timer to do it with a single operator instead:

return Observable.timer(0, 1000)
  .flatMapTo(this.http.get(this.apiURL))
  .map(this.extractData)
  .catch(this.handleError);

这篇关于开始首次呼叫IntervalObservable瞬间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆