【问题标题】:Running a http call every two mins每两分钟运行一次http调用
【发布时间】:2017-07-13 10:33:45
【问题描述】:

我有一个具有该功能的服务:

fetchChatCirclesFromServer(): Observable<Response> {
    return this.http.post(
      this.apiurl + '/chat-circle/getChatCircles',
      {user: {loc: {lat: this.lat, lng: this.lng}}},
      {headers: this.headers}
    )
  }

我在组件中订阅这个 Observable,如下所示:

ngOnInit() {
  this.chatCircleService.fetchChatCirclesFromServer()
  .subscribe(resp => {
    this.chatCircles = resp.json().chatCircle
    this.chatCircleService.joinChatCircle(this.chatCircles[0].id)
  })
}

如何转换 fetchChatCirclesFromServer() 函数,使其每 2 分钟调用一次 http.post 将响应发送回组件? 我已经尝试过在类似问题上发布的 Observable.interval().timeInterval() 解决方案,但在我的情况下甚至无法编译。 谢谢

【问题讨论】:

  • 为什么不编译?你得到什么错误?时间间隔解决方案的实现是什么?

标签: angular http rxjs


【解决方案1】:
ngOnInit() {
  Observable.timer(0, 120000)  // starting immediately, calling every 120seconds (or 2 minutes)
    .switchMap(() => this.chatCircleService.fetchChatCirclesFromServer())  // then switch to the request-stream from the service
    .subscribe(resp => {
        this.chatCircles = resp.json().chatCircle
        this.chatCircleService.joinChatCircle(this.chatCircles[0].id)
      })
}

注意 1:不要忘记关闭订阅,以防您的组件在应用程序运行时的任何时候被删除。

注意 2.interval(n: number) 不会立即发出,但只会在第一个间隔之后发出,在这种情况下,这将在 2 分钟后发出,而使用timer(initialDelay, interval),您可以定义自定义初始延迟,你可以设置为 0。

【讨论】:

  • 这是正确编译,但是 chrome 控制台抛出错误说计时器不是 observable 的函数,即使在从 'rxjs/Observable' 和 'rxjs/observable/timer' 导入 { Observable } 之后也是如此。还有什么我需要导入的吗?
  • import "rxjs/add/observable/timer";
【解决方案2】:

试试

fetchChatCirclesFromServer(): Observable<Response> {
    return Rx.Observable.interval(120000).flatMap(() => {
        return this.http.post(
            this.apiurl + '/chat-circle/getChatCircles',
            {user: {loc: {lat: this.lat, lng: this.lng}}},
            {headers: this.headers}
        )
    });
}

【讨论】:

  • 这是编译,但在 chrome 控制台上它的抛出错误 Observable.interval 不是一个函数,即使在导入 'rxjs/observable/interval' 之后也是如此。还有什么我必须导入的吗?
猜你喜欢
  • 2019-11-04
  • 2012-08-26
  • 1970-01-01
  • 2019-06-09
  • 2015-03-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
相关资源
最近更新 更多