简体   繁体   English

如何使用Rxjs'interval'运算符在每次timeInterval中执行Angular 2 http调用?

[英]How to execute Angular 2 http call every timeInterval with Rxjs 'interval' operator?

I have this simple method in my service : 我在服务中有以下简单方法:

 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();
}

It return a stream of object which contain informations about user's notification. 它返回一个对象流,其中包含有关用户通知的信息。 i would like to execute this call every 5 second with interval operator without using setTimeout ? 我想使用间隔运算符每5秒执行一次此调用而不使用setTimeout吗?

When i try this : 当我尝试这个:

 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();
}

I have an error. 我有一个错误。 Any Suggestion ? 有什么建议吗?

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> }
}

A few notes: 1. You must subscribe to the returned value to start the calls. 一些注意事项:1.您必须订阅返回的值才能开始调用。 2. Your data service is statefull, this might create race condition where 2 different clients set the url and then invoke it, consider converting the get to a stateless function: get(url) , in which case your code will be 2.您的数据服务是全状态的,这可能会导致竞争状态,其中2个不同的客户端设置url然后调用它,请考虑将get转换为无状态函数: get(url) ,在这种情况下,您的代码将是

notify(userID: string) {
  return Observable.interval(5000)
    .map(() => this.baseUrl + '/notification/GetUnseen?userId=' + userID)
    .switchMap(url => this.dataService.get(url))
    .map(response => ....{ <your handler> }
}

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

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