I have 3 observables that i need to chain, result from first one is used in the other 2. They must run in order and each one must wait for the previous one to finish. Is it possible to chain then without nesting?
public observable1(): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(url, "", requestOptions);
}
public observable2(data1url): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(data1url, "", requestOptions);
}
public observable3(data1url): Observable<Response> {
let headers = new Headers();
headers.append("Content-Range", "bytes */*");
let requestOptions = new RequestOptions({headers: headers});
return this.http.put(data1url, "", requestOptions);
}
This is the only way i found to chain them but they are still nested, is it posible to do this and not to nest them?
public doHttpProcess() {
return this.observable1().concatMap(result1 => {
return this.observable2(result1.json().data1)
.concatMap(result2 => {
return this.observable3(result1.json().data1);
});
});
}
Thank you very much for your help
You are almost there, you just need to remove the second nesting and you can chain the concatMap
calls
public doHttpProcess() {
return this.observable1()
.concatMap(result1 => this.observable2(result1.json().data1).map(result2 => ({ result1, result2 }))
.concatMap(({ result1, result2 }) => this.observable3(result1.json().data1));
}
And if you don't need result2
to generate the last observable, you can simplify to
public doHttpProcess() {
return this.observable1()
.concatMap(result1 => this.observable2(result1.json().data1).mapTo(result1))
.concatMap(result1 => this.observable3(result1.json().data1));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With