简体   繁体   English

如何使用Angular 2中的rxjs按间隔请求异步

[英]How to Request Async by interval using rxjs in Angular 2

I want to set interval in http request using rxjs. 我想使用rxjs在http请求中设置间隔。 I need to send data on server from n seconds after request finish. 我需要在请求完成后n秒内在服务器上发送数据。

Observable.interval(10000)
                  .?(() => {
                      //request for server. return Observable
                      return this.getData();
                  })
                  .subscribe(() => {
                      console.log("Request done. After 10 second will be next request");
                  });

UPDATE based on .expand() suggested by Mark UPDATE基于Mark建议的.expand()

ngOnInit() {
  this.getData()
    .expand(() => Rx.Observable.timer(10 * 1000)
      .concatMap(() => this.getData())
    )
    .subscribe(data => {
      console.log('received new data', data);
    });
}

private getData() {
  return Observable.timer(5000)
    .do(() => console.log("timer"));
}

i think you want to request server for something every few seconds. 我想你想要每隔几秒就要一次服务器。 can you try this way 你能这样试试吗?

make sure you have imported import {Observable} from 'rxjs/Rx' if you don't import it we get observable not found error sometimes 确保你从'rxjs / Rx'导入导入{Observable}如果你不导入它我们得到可观察到的错误有时候会发现错误

working plnkr http://plnkr.co/edit/vMvnQW?p=preview 工作plnkr http://plnkr.co/edit/vMvnQW?p=preview

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';

@Component({
    selector: 'app',
    template: `
      <b>Angular 2 HTTP request every 5 sec RxJs Observables!</b>
      <ul>
        <li *ngFor="let doctor of doctors">{{doctor.name}}</li>
      </ul>

      `
})

export class MyApp {
  private doctors = [];

  constructor(http: Http) {
    Observable.interval(5000)
    .switchMap(() => http.get('http://jsonplaceholder.typicode.com/users/')).map((data) => data.json())
        .subscribe((data) => {
          this.doctors=data; 
           console.log(data);// see console you get output every 5 sec
        });
  }
}

see google inspect console you will be getting new data every 5 sec 看谷歌检查控制台,你将每5秒获得一次新数据

Your usecase is an excellent case for the .expand operator which can recursively execute and return new values. 您的.expand.expand运算符的一个很好的例子,它可以递归地执行和返回新值。 See this snippet in which i have added a lot of timestamp + debug logging to clarify what is going on. 请参阅此片段,其中我添加了大量时间戳+调试日志记录以阐明正在发生的事情。

 function getData() { // simulate remote call which can take some time return Rx.Observable.of('') .timestamp() .do(i => console.log(`[debug] Going to fetch data from server @${i.timestamp}`)) .map(i => 'the new JSON blob of data to use') // this would be your actual http.get call .delay(1500) .timestamp() .do(i => console.log(`[debug] Data retreived from server @${i.timestamp}`)); } getData() .expand(_ => Rx.Observable.of('') // we need something to delay upon .timestamp() .do(i => console.log(`[debug] Waiting 1sec for next getData ${i.timestamp}`)) .delay(1000) .concatMap(() => getData()) ) .take(5) .subscribe(val => console.log(`New data received @${val.timestamp} : ${val.value}`)) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.0.3/Rx.js"></script> 

so initially you subscribe to the getData() and expand its value to recursively delay for time before retrieving the next getData() . 所以最初你订阅了getData()并扩展它的值,以便在检索下一个getData()之前递归delay一段时间。 No subjects are involved in this approach and your subscription stays available for receiving the new values. 此方法不涉及任何主题,您的订阅仍可用于接收新值。

I've read the comments you put in that deleted answer. 我已经阅读了你在删除的答案中的评论。 You want to send a request, then 10 seconds after receiving a response send another request. 您想发送请求,然后在收到响应后10秒发送另一个请求。

That's quite complex, but doable... I think something like this should work: 这很复杂,但可行......我认为这样的事情应该有效:

let responseSubject = new Rx.BehaviourSubject({});
responseSubject
    .delay(10000)
    .flatMap(() => {
        return http.get(...)
    })
    .subscribe((res) => {
        responseSubject.onNext({});
        // Your stuff here
    });

Here I'm setting up a behaviour so I can feedback when we get a response. 在这里,我正在设置一个行为,以便在收到回复时能够提供反馈。 Then setup a stream that after 10 seconds of a request, it makes the request and yields the response. 然后设置一个流,在请求10秒后,它发出请求并产生响应。

Edit: I'm missing something... the first request will take 10 seconds before it starts. 编辑:我错过了一些东西......第一个请求在开始前需要10秒钟。 Then I would rewrite as: 然后我会重写为:

let responseSubject = new Rx.ReplaySubject(1);
responseSubject
    .delay(10000)
    .startWith({})
    .flatMap(() => {
        return http.get(...)
    })
    .subscribe((res) => {
        responseSubject.onNext({});
        // Your stuff here
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM