Skip to content

Instantly share code, notes, and snippets.

@gsans
Created January 14, 2017 15:00
Show Gist options
  • Save gsans/876b6032dbd1d99508bf221a9b14b25c to your computer and use it in GitHub Desktop.
Save gsans/876b6032dbd1d99508bf221a9b14b25c to your computer and use it in GitHub Desktop.
Retry a HTTP get with new configuration parameters each retry
//our root app component
import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {HttpModule, Http} from '@angular/http';
import 'rxjs/add/operator/do';
import 'rxjs/add/observable/timer';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/mergeMap';
import 'rxjs/add/operator/retryWhen';
import 'rxjs/add/operator/delay';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
</div>
`,
})
export class App {
name:string;
constructor(private http: Http) {
Observable.timer(0).mergeMap(x=> {
return this.http.get('data.json', this.configObject())
.do(x => throw(x))
.map(res=>res.json());
})
.retryWhen(e => e.delay(2000))
.subscribe();
/*this.http.get('data.json', this.configObject())
.do(x => throw(x))
.map(res=>res.json())
.retryWhen(e => e.delay(2000))
.subscribe();*/
}
configObject(){
console.log('*');
}
}
@NgModule({
imports: [ BrowserModule, HttpModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
@jplew
Copy link

jplew commented Feb 9, 2018

thank you for sharing this example, I ended up adapting it for my needs. In my case, I needed to call an API with a random string parameter each time until one string passed the test.

  getLetterPair(): Observable<string> {
    return Observable.timer(0).pipe(
      mergeMap(x => {
        this.random = this.padWithRandomLetter()
        return this.wordBankService.checkIfValidFragment(this.random).pipe(
          map(bool => {
            if (!bool) {
              throw (bool)
            }
            return this.random
          })
        )
      }),
      retry(26)
    )
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment