Combine Multiple Observables Using combineLatest In Angular App

In this article, I am going to show you the benefits of using the combineLatest operator in an Angular application. Whenever we have multiple independent calls, then usually we do call them as separate calls. Let’s consider that we have multiple HTTP requests to get the master date to load different web controls. So far, we have been calling these independent calls in our component’s ngOnInit() lifecycle hook method. Now, Angular provides a new feature to call multiple HTTP requests by combining them - combineLatest operator. Here, the question is: what is special with the combineLatest operator?

My answer is "Performance". You know, performance is a big concern with each and every application. This operator is best used when we have multiple independent HTTP requests. We can make multiple sequential HTTP requests by combining them using the combineLatest operator.

In the following, I am going to show you the usage of combineLatest operator with a concrete example.

Step 1 - Create a service class

test-service.ts

  1. import { Injectable } from '@angular/core';  
  2. import { Observable } from 'rxjs/Rx';  
  3.   
  4. @Injectable()  
  5. export class TestService {  
  6. constructor() { }  
  7.   
  8. getSampleMasterData1(): Observable<any> {  
  9.     return Observable.fromPromise(this.proxyService.get(`yourServiceURL`));  
  10. }  
  11.   
  12. getSampleMasterData2(): Observable<any> {  
  13.     return Observable.fromPromise(this.proxyService.get('yourServiceURL'));  
  14. }  
  15.   
  16. getSampleMasterData3(): Observable<any> {  
  17.     return Observable.fromPromise(this.proxyService.get('yourServiceURL'));  
  18.    }  
  19. }  

In the above code snippet, I have created three independent HTTP requests to get the master data from different data sources.

Step 2

Now, let us call the created HTTP requests in our component file using combineLatest operator.

test.component.ts

  1. import { TestService } from test.service';  
  2.   
  3. @Component({  
  4.     selector: 'test-view',  
  5.     templateUrl: './test.component.html',  
  6.     styleUrls: ['./test.scss'],  
  7.     encapsulation: ViewEncapsulation.None,  
  8.     providers: []  
  9. })  
  10. export class TestComponent implements OnInit {  
  11. masterDataList1: Array<any>;  
  12. masterDataList2: Array<any>;  
  13. masterDataList3: Array<any>;  
  14.   
  15.   
  16. constructor(private testService: TestService) {}  
  17.   
  18. public getSampleMasterData1(): Observable<Array<any>> {  
  19.     return this. testService. getSampleMasterData1().map((response) => {  
  20.         return response;  
  21.     }).catch((error) => {  
  22.         return Observable.throw(error);  
  23.     });  
  24. }  
  25.   
  26. public getSampleMasterData2(): Observable<Array<any>> {  
  27.     return this. testService. GetSampleMasterData2().map((response) => {  
  28.         return response;  
  29.     }).catch((error) => {  
  30.         return Observable.throw(error);  
  31.     });  
  32. }  
  33.   
  34. public getSampleMasterData3(): Observable<any> {  
  35.     return this. testService. GetSampleMasterData3().map((response) => {  
  36.         return response;  
  37.     }).catch((error) => {  
  38.         return Observable.throw(error);  
  39.     });  
  40. }  
  41.   
  42. const  masterData1Observable = this.getSampleMasterData1();  
  43. const masterData2Observable = this.getSampleMasterData2();  
  44. const masterData3Observable = this.getSampleMasterData3();  
  45.   
  46. ngOnInit() {  
  47.   
  48. Observable.combineLatest(masterData1Observable, masterData2Observable, masterData3Observable).subscribe(([masterData1, masterData2, masterData3]) => {  
  49.      this.masterDataList1 = masterData1;  
  50.      this.masterDataList2 = masterData2;  
  51.      this.masterDataList3 = masterData3;  
  52.     }  
  53. );  
  54. }                                 
  55. }  

If you observe the above code snippet, getSampleMasterData1(), getSampleMasterData2() and getSampleMasterData3() are the Observable methods. I have assigned those Observable methods to the constant variables and then subscribed the created Observables using the Observable.combineLatest and passed the constant variables as input parameters.

Since I have subscribed three observables and, of course, I am expecting three responses (in the above code snippets, masterData1, masterData2, and masterData3 are three responses) and in the success block I am assigning responses to the class properties (this.masterDataList1,  this.masterDataList1 and this.masterDataList1). Once the responses are assigned to the class properties, we can use them in our View page.

You can refer to a few more articles on Angular,

I would appreciate your valuable feedback. Happy reading :)


Similar Articles