In the context of an Angular component I have 2 observables.
Requirements
Approach
What is the best way to achieve my requirements?
getData1$ = this.myService.getData1();
getData2$ = this.myService.getData2();
constructor(private myService: MyService) {
this.getAllData();
}
getAllData() {
concat(this.getData1$, this.getData2$)
.pipe(finalize(() => console.log('always called')))
.subscribe(() => {
error: console.log('one or more data fetches have had an error');
complete: console.log('all data fetches have succeeded');
});}
Use a concat
, it will execute in series one by one, then we can use toArray
which will collect all source emissions and emits them as an array when the source completes.
getData1$ = this.myService.getData1();
getData2$ = this.myService.getData2();
constructor(private myService: MyService) {
this.getAllData();
}
getAllData() {
concat(this.getData1$, this.getData2$).pipe(toArray())
.subscribe({
next: (data: any) => console.log('success!'),
error: () => console.log('one or more data fetches have had an error'),
complete: () => console.log('all data fetches have succeeded'),
});
}