Attempting to implement a loading spinner in my Angular application has been quite the journey.
Stumbled upon an intriguing tutorial at this link (https://medium.com/swlh/angular-loading-spinner-using-http-interceptor-63c1bb76517b).
Everything was going smoothly until I hit the final step, where creating the intercept function became necessary.
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor, HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators'
import { LoadingService } from './loading.service';
/**
* Class designed to intercept http requests. Initializes loadingSub property in LoadingService as true on request start. Once request is completed and response received, sets loadingSub to false. In case of error during request handling, also sets loadingSub to false.
* @class {HttpRequestInterceptor}
*/
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
/**
*
* @param _loading
*/
constructor(
private _loading: LoadingService
) { }
/**
* Called at the beginning of every HTTP request. Activates loading spinner at start.
* @param request
* @param next
* @returns
*/
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this._loading.setLoading(true, request.url);
return next.handle(request)
.pipe(catchError((err) => {
this._loading.setLoading(false, request.url);
return err;
}))
.pipe(map<HttpEvent<any>, any>((evt: HttpEvent<any>) => {
if (evt instanceof HttpResponse) {
this._loading.setLoading(false, request.url);
}
return evt;
}));
}
}
The first pipe seems fine.
But now, there's a glaring red underline indicating an issue with the second pipe. The error message reads:
Argument of type 'OperatorFunction<HttpEvent, any>' is not assignable to parameter of type 'OperatorFunction<unknown, any>'. Type 'unknown' is not assignable to type 'HttpEvent'.ts(2345)
https://i.sstatic.net/Jp7LNqi2.png
In both VSCode (blue underline) and Microsoft VS (purple underline), the error persists, implying it's a coding issue rather than just a quirk of the IDE...
This article dates back to June 2020 (4 years ago), leading me to think that there may have been changes in how Angular observables operate?
I've only been diving into Angular for a week, and TypeScript is still somewhat foreign to me, so please excuse any oversights on my part. Any guidance would be greatly appreciated, as I'm unsure about the next steps...
If any Stack Overflow experts have insights, they'd be immensely valuable.
Thank you!