I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingRequests, I have implemented a counter using Angular's HttpInterceptor; and for locationChanged, I am subscribing to Router's NavigationStart/NavigationEnd events.
httpPendingRequests: BehaviorSubject<number>;
locationChanged: BehaviorSubject<boolean>;
To subscribe to these two Observables, I am using concatMap with the following code:
this.locationChanged.pipe(
concatMap(changed => {
console.log('location change:' + changed);
if (changed) {
return this.httpPendingRequests;
} else {
return of(0);
}
}),
map(count => count > 0)
).subscribe(val => {
console.log('isloading: ' + val);
});
My expectation was that this would only log 'isloading' to the console when both the location has changed and there are pending requests. It does work as expected in this case. However, I noticed that it also logs the 'isloading' message even when there are only pending HTTP requests without any change in location. This situation confused me because I thought that the operator would ensure that the Observables are subscribed in order. If the first one (location change) does not emit, then the second one (pending request) should not be triggered. Am I misunderstanding this concept?
In addition, I tried other methods like zip, forkJoin, combineLatest to combine Observables, but they all behaved the same way by triggering the subscription only once. I am uncertain about what went wrong with them either.
If more information is needed, feel free to ask. Thank you in advance!