I’m trying to use my interceptor to set a boolean and then use that boolean to hide/show a progress bar. I new to the function based interceptors and guards so I’m not sure if I’m doing this right. The interceptor is working but for some reason the progress bar never shows up when I make an http request. I feel like maybe my inject is just injecting a brand new instance of my data service, but I’m not sure. Any help would be appreciated!
Here is my data service variable declaration:
public isLoading = new BehaviorSubject<boolean>(false);
isLoading$ = this.isLoading.asObservable();
Here is the interceptor:
import { HttpEvent, HttpRequest, HttpHandlerFn, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { AuthService } from './auth.service';
import { Observable, throwError } from 'rxjs';
import { mergeMap, catchError, map, finalize } from 'rxjs/operators';
import { DataService } from './data.service';
const settings = require('../configuration/settings?v=1.0.0');
export const Interceptor: HttpInterceptorFn = (
req: HttpRequest<any>,
next: HttpHandlerFn
): Observable<HttpEvent<any>> => {
const _data = inject(DataService);
const authService = inject(AuthService);
// Use different request for API vs Graph (not implemented)
// console.log(req.url)
_data.isLoading.next(true)
return authService.getAccessTokenSilently$().pipe(
mergeMap(token => {
// console.log('interceptor: access: ' + token);
const tokenReq = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
VersionVerify: 'true',
Version: settings.version,
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next(tokenReq).pipe(
map(event => {
_data.isLoading.next(false)
return event;
}),
catchError(err => {
if (err && err.error && err.error.message && err.error.message.match(/^Version:/)) {
let data = err.error.data;
if (data != null && data.version != null) {
console.log("Version (ours)|(curr): (" + settings.version + ")|(" + data.version + ")")
}
// Can we get browser specific refresh instructions, or is ctrl-F5 universal?
let msg = "You do not have the current version. Please do a hard-refresh of your browser (Ctrl-F5)";
// this._alertService.error(msg);
// Send the request again, but do not verify version
const versionReq = req.clone({
setHeaders: {
Authorization: `Bearer ${token}`,
'Cache-Control': 'no-cache',
Pragma: 'no-cache'
}
});
return next(versionReq).pipe(
map(event => {
return event;
}),
catchError(err => {
// this._alertService.error(err.error.message);
return throwError(() => err);
})
)
}
return throwError(() => err)
})
)
}),
catchError(err => throwError(() => err))
)
};
Here is my app.component.html:
<div class="flex flex-column">
@if(_dataService.isLoading$ | async) {
<p-progressBar mode="indeterminate" [style]="{ height: '6px' }"></p-progressBar>
}
<app-top-menu></app-top-menu>
<p-toast></p-toast>
<router-outlet></router-outlet>
</div>