I'm struggling to understand how to monitor for new values in an observable from a service. My ultimate objective is to integrate an interceptor, a service, and a directive to show loading information to the user. I have set up an interceptor to listen for http calls:
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http';
import { Observable, pipe } from 'rxjs';
import { LoadingService } from '../loading.service';
import { map, finalize } from 'rxjs/operators';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
constructor(private loadingSrv: LoadingService) {}
public intercept(req, next): Observable<HttpEvent<any>> {
if (req.url === 'graphql') {
console.log('first', req);
this.loadingSrv.saveRequest(req);
}
return next.handle(req).pipe(
map(el => {
if (req.url === 'graphql') {
}
return el;
}),
finalize(() => {
console.log('final', req);
})
);
}
}
If a request is detected, it should trigger the loading service and execute a saving function.
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class LoadingService {
public loadingQueries: BehaviorSubject<[]> = new BehaviorSubject(null);
constructor() {}
saveRequest(req) {
this.loadingQueries.next(req);
}
}
The loading service will emit the new request value to the behavior subject. Now, my goal is to subscribe to this BehaviorSubject from a directive.
import { Directive, Input, OnInit, TemplateRef, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { LoadingSpinnerComponent } from './loading-spinner.component';
import { LoadingService } from './loading.service';
@Directive({
selector: '[showLoadingSpinner]'
})
export class ShowLoadingSpinnerDirective implements OnInit {
@Input('showLoadingSpinner') query: any;
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private loadingSpinner: LoadingSpinnerComponent,
private factoryResolver: ComponentFactoryResolver,
public loadingSrv: LoadingService
) {}
ngOnInit(): void {
const factory = this.factoryResolver.resolveComponentFactory(LoadingSpinnerComponent);
console.log(this.query);
this.loadingSrv.loadingQueries.subscribe(console.log);
}
}
My issue now is that the subscriptions are not recognizing new values. Perhaps because the service here is a new instance? How can I ensure the directive listens for any changes to detect when a query is initiated and completed?