2016-08-25 105 views
5

如何在retryWhen中設置延遲?Observable「retryWhen」delay

import 'rxjs/add/operator/retry'; 
import 'rxjs/add/operator/retrywhen'; 

...

constructor(http: Http) { 

    var headers = new Headers(); 
    headers.append('Content-Type', 'text/plain'); 
    http.post('https://mywebsite.azurewebsites.net/account/getip', "", { headers: headers }) 
    .retryWhen(errors => { 
       return errors.delay(1000); // errors is not a function 
       }) 
      (event) => { 
       // handle events 
       this.ip = event.json(); 
      }, 
      (error) => { 
       console.error(error); 
       toastr.error('No connection to server. Please reload the page!') 

      } 
      ); 
} 

我得到的錯誤:errors is not a function

+0

檢查此鏈接http://www.unknownerror.org/opensource/ReactiveX/RxJava/q/stackoverflow/22066481/rxjava-can-i-use-retry-but-with-delay – rashfmnb

+0

是這是你的確切代碼?如果是這樣,你有語法錯誤(括號不匹配等)。你能格式化代碼嗎? –

+0

這不是我的代碼,我剛剛從這裏找到了解決方案,這就是爲什麼我在這裏分享它的原因 – rashfmnb

回答

6
import {Http, Headers, Response} from '@angular/http'; 

http.get('http://jsonplaceholder.typicode.com/posts/1/commentsss') 
    .retryWhen(e => e.scan<number>((errorCount, err) => { 
     if (errorCount >= 10) { 
      throw err; 
     } 
     return errorCount + 1; 
    }, 0).delay(1000)) 
    .subscribe(r => console.log(`Sub: ${r}`)) 

這次重試10次,延遲1秒。

plnkr