The log lines inside forkJoin are not called

Viewed 46

I have a method.

private getData() {
     console.log('Begin');
     const sub1 = this.http['url1'].get();
     const sub2 = this.http['url2'].get();
     const sub3 = this.http['url3'].get();
     const sub = forkJoin([sub1, sub2, sub3]).subscribe(([res1, res2, res3]) => {
         console.log('fork join');
         this.list1 = res1 as ProjectDto[];
         this.list2 = res2 as Array<MyTest>;
         this.list3 = res3 as Array<MyTest>;
         sessionStorage.setItem('a', JSON.stringify(this.list1));
         sessionStorage.setItem('b', JSON.stringify(this.list2));
         sessionStorage.setItem('c', JSON.stringify(this.list3));
         console.log('set items');
     });
     console.log('Completed');
   }

The method was called. However two log lines inside forkJoin were not called at all. So I don't know whether I get the data from service successfully. I use rxjs 5.5.6.

UPDATE:

My bad, I just found they were actually printed out as the service took a very long time. So the question becomes how to print the logs synchronously. Now they print Begin and Completed first.

2 Answers

The third parameter of subscribe will accept a callback and will be invoked when the stream is completed

 const sub = forkJoin([sub1, sub2, sub3]).subscribe(([res1, res2, res3]) => {
     console.log('fork join');
     this.list1 = res1 as ProjectDto[];
     this.list2 = res2 as Array<MyTest>;
     this.list3 = res3 as Array<MyTest>;
     sessionStorage.setItem('a', JSON.stringify(this.list1));
     sessionStorage.setItem('b', JSON.stringify(this.list2));
     sessionStorage.setItem('c', JSON.stringify(this.list3));
 },null,()=>console.log('complete'));

You should put console.log('Completed'); inside of the subscribe since the subscribe is asynchronous and happens at a later point in time.

But if you want the structure to stay the same, you can do promise like programming.

import { take } from 'rxjs/operators';
....
private async getData(): Promise<boolean> {
     console.log('Begin');
     const sub1 = this.http['url1'].get();
     const sub2 = this.http['url2'].get();
     const sub3 = this.http['url3'].get();
     const [res1, res2, res3] = await forkJoin([sub1, sub2, sub3]).pipe(take(1)).toPromise();
     console.log('fork join');
     this.list1 = res1 as ProjectDto[];
     this.list2 = res2 as Array<MyTest>;
     this.list3 = res3 as Array<MyTest>;
     sessionStorage.setItem('a', JSON.stringify(this.list1));
     sessionStorage.setItem('b', JSON.stringify(this.list2));
     sessionStorage.setItem('c', JSON.stringify(this.list3));
     console.log('set items');
     console.log('Completed');
     return Promise.resolve(true);
   }
Related