I'm working on a Angular 4 project and I'm new with Observable.
My goal is to execute one function after the result of three HTTP requests and enrich my models with HTTP request results.
I resolved my problem with observable like following code but I think this is not the correct way:
function loadData(callback: Function): void {
this.httpRequestUno().subscribe(next => {
this.httpRequestDue().subscribe(next => {
this.httpRequestTre().subscribe(next => {
callback();
}, error => {
console.log(error);
});
}, error => {
console.error(error);
});
}, error => {
console.error(error);
});
}
function httpRequestUno():Observable<any>{
let self = this;
return new Observable<any>((observer) => {
// my http request and...
self.attributo1 = httpResult;
observer.next(1);
});
}
function httpRequestDue():Observable<any>{
let self = this;
return new Observable<any>((observer) => {
// my http request and...
self.attributo2 = httpResult;
observer.next(2);
});
}
function httpRequestTre():Observable<any>{
let self = this;
return new Observable<any>((observer) => {
// my http request and...
self.attributo3 = httpResult;
observer.next(3);
});
}
Does RxJS allow to combine multiple actions like following pseudo-code?
function loadData(callback: Function): void {
this.httpRequestUno().combine(this.httpRequestDue).combine(this.httpRequestTre).subscribe(result => {
callback();
});
}
Is there a way to pass all results in one parameters like following pseudo-code?
this.httpRequestUno().combine(this.httpRequestDue).combine(this.httpRequestTre).subscribe(result => {
let httpRequestUnoResult = result[0];
let httpRequestDueResult = result[1];
let httpRequestTreResult = result[2];
callback();
});
[EDIT]
I've tried Oscar's solution. The problem is that subscribe callback are not executed but if I add one observer.completed() in one function the "completed callback" is executed but I cannot access to data.
I reproduced my case there https://jsfiddle.net/2n6b0ug3/
Thank you a lot