首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用Rxjs 'interval‘操作符执行每个timeInterval的角2 http调用?

如何使用Rxjs 'interval‘操作符执行每个timeInterval的角2 http调用?
EN

Stack Overflow用户
提问于 2016-12-02 13:42:25
回答 1查看 743关注 0票数 0

我有一个简单的服务方法:

代码语言:javascript
复制
 notify(userID: string) {
    let _URL = this.baseUrl + '/notification/GetUnseen?userId=' + userID;
     this.datatService.set(_URL);
    return this.datatService.get()
        .flatMap((response) =>
           response.json().slice())
           .distinct();
}

它返回一个对象流,其中包含有关用户通知的信息。我想在不使用setTimeout的情况下每5秒用interval操作符执行这个调用?

当我尝试这个:

代码语言:javascript
复制
 notify(userID: string) {
    let _URL = this.baseUrl + '/notification/GetUnseen?userId=' + userID;
     this.datatService.set(_URL);
    return this.datatService.get()
        **.interval(5000)**
        .flatMap((response) =>
           response.json().slice())
           .distinct();
}

我有个错误。有什么建议吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-02 13:55:17

代码语言:javascript
复制
notify(userID: string) {
  return Observable.interval(5000)
    .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
    .switchMap(url => {
      this.dataService.set(url);
      return this.dataService.get();
    })
    .map(response => ....{ <your handler> }
}

注意: 1.您必须订阅返回的值才能开始调用。2.您的数据服务是状态的,这可能会创建两个不同客户端设置url然后调用它的争用条件,考虑将get转换为无状态函数:get(url),在这种情况下,您的代码将是

代码语言:javascript
复制
notify(userID: string) {
  return Observable.interval(5000)
    .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
    .switchMap(url => this.dataService.get(url))
    .map(response => ....{ <your handler> }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40933599

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档