2016-12-02 16 views
0

我有我的服务这种简单的方法:如何在每次使用Rxjs'interval'运算符时执行Angular 2 http调用?

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

它返回对象的流包含关于用户的通知信息。我想用间隔运算符每5秒执行一次该调用,而不使用setTimeout?

当我试试这个:

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

我有一个错误。 有何建议?

回答

2
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.您的数据服务是有状态的,这可能会产生竞态条件,其中2级不同的客户端设置的URL,然后调用它,可以考虑转换到一个无状态的功能: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> } 
} 
+0

我正在订阅组件中的方法,thx是关于statfull函数的注释+1 –

相关问题