I need advice. I'm quite new to RxJS so I want to use it correctly. I need to get two different arrays from API. I want to finish this operation only when both of them are complete because I need to send them to the child component (The child component has two different list boxes which depend on each other).
I want to store these Observables in:
departments$: Observable<IDepartment[]>;
workers$: Observable<IWorker[]>;
Solution for this problem:
departments$ = this.http.get<string[]>('api/departments')
.pipe(
tap(data => console.log(JSON.stringify(data))),
catchError(this.handleError)
);
workers$ = this.http.get<string[]>('api/workers')
.pipe(
tap(data => JSON.stringify(data))),
catchError(this.handleError)
);
departmentsAndWorkers$ = forkJoin({
departments$: this.departments$,
workers$: this.workers$
})
.pipe(
tap(data => console.log(JSON.stringify(data))),
catchError(this.handleError)
)
CodePudding user response:
You are looking for forkJoin
RxJS operator. It will emit a tuple value when all the requests are completed. Read more about it: https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
CodePudding user response:
You can try using forkJoin like this :
forkJoin([departments$,workers$]).subscribe((resp: any) => {
// resp[0] : departments$
// resp[1] : workers$
},
errors=>{
}
});
CodePudding user response:
You can use forkJoin: Wait for Observables to complete and then combine last values they emitted; complete immediately if an empty array is passed. https://rxjs.dev/api/index/function/forkJoin
or combineLatest: Whenever any input Observable emits a value, it computes a formula using the latest values from all the inputs, then emits the output of that formula. https://rxjs.dev/api/index/function/combineLatest