每1分钟回复一次?

时间:2017-06-14 09:26:49

标签: javascript angular typescript ionic2 rxjs

有没有办法连续每1分钟回复一次承诺? 我正在尝试这样的事情,但它在开始时只返回一次承诺:

    startWork() {

    this.dataService.startPing(details).then((result) => {
      this.timeSlotsRefresh();
    }, (err) => {
      console.log(err);
    });
  }

然后:

startPing() {
let startingTime = new Date();

return new Promise((resolve, reject) => {

  let source = Rx.Observable.timer(startingTime, 60000).timeInterval().pluck('interval');


  this.Subscription = source
    .subscribe(data => {

          this.http.post('http://localhost:63203/api/Ping', JSON.stringify(this.offlinePings[i]))
            .map(res => res.json())
            .subscribe(data => {
              resolve(data);
            }, (err) => {
              reject(err);
            });
    });
});

}

它必须每1分钟通知此函数调用this.timeSlotsRefresh();来刷新数据,我该如何实现?

1 个答案:

答案 0 :(得分:2)



@Injectable
class Ping {
  readonly observable = Rx.Observable.interval(60000);
  
  subscribe(...cbs) {
    return this.observable.subscribe(...cbs);
  }
}


@Component
class Foo implements OnInit, onDestroy {
  private subscription = null;
  
  constructor(private ping: Ping) {}
  
  onPing(count) {}
  onPingError(error) {}
  onPingFinish() {}
  
  ngOnInit() {
    this.subscription = this.ping.subscribe(
      (...d) => this.onPing(...d),
      (...e) => this.onPingError(...e),
      (...f) => this.onPingFinish(...f)
    );
  }
  
  ngOnDestroy() {
    this.subscription.unsubscribe()
  }
}




Promise只能使用一次,您可能需要类似于流媒体的内容,Observable可能更适合。

rxinterval运算符一起使用:



var source = Rx
    .Observable
    .interval(2000 /* ms */)
    .map(id => fetch(`https:\/\/jsonplaceholder.typicode.com\/posts\/${id}`).then(res => res.json()))
;

var subscription = source
  .subscribe(post => console.log('New Post', post))
;

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.4.0/Rx.js"></script>
&#13;
&#13;
&#13;

相关问题