Lumix
Lumix

Reputation: 111

How to change parameter in Observable (RxJs)

I use HTTP provider in Angular 2 for data loading from API.

return this.http.post(url, urlSearchParams.toString(), {
        headers: this.getHttpHeaders()
    })
    .retryWhen((error) => {
        return this.handleRetryError(error);
    })

When there is no or old session I create new one in this.handleRetryError(error) and fill headers with it. (method getHttpHeaders() returns array with headers)

RetryWhen tries to do this post again, but there is unchanged (old) headers from first round.

Is there any chance to change headers parameter for http.post from .readyWhen?

Thank you very much for help :)

Upvotes: 11

Views: 2405

Answers (3)

Gerard Sans
Gerard Sans

Reputation: 2279

You need to wrap the Observable and retry the resulting outer Observable so each time it executes again.

Observable.of(1).mergeMap(x=> {
  return this.http.get('data.json', this.configObject())
  .do(x => throw(x))
  .map(res=>res.json());
})
.retryWhen(e => e.delay(2000))
.subscribe();

for your code

return Observable.of(1).mergeMap(x => { 
    return this.http.post(url, urlSearchParams.toString(), {
      headers: this.getHttpHeaders()
    });
  })
  .retryWhen(e => this.handleRetryError(e))

Upvotes: 1

Thomas Kuipers
Thomas Kuipers

Reputation: 1

You could possibly keep a reference to a headers variable outside that function, and then modify that variable inside the retryWhen function.

let headers = this.getHttpHeaders();

return this.http.post(url, urlSearchParams.toString(), {
    headers: headers
})
.retryWhen((error) => {
    headers.foo = "bar";

    return this.handleRetryError(error);
})

Upvotes: 0

Nypan
Nypan

Reputation: 7246

Try this:

return Observable
    .defer(() => {
        this.http.post(url, urlSearchParams.toString(), {
            headers: this.getHttpHeaders()
        });
    })
    .retryWhen(errors => {
        this.handleRetryError(errors);
        return errors.delay(200)
    });

Upvotes: 0

Related Questions