After experimenting with injecting services in Angular, I encountered an issue when trying to call LogService within GlobalErrorHandler. Despite my best efforts, the code below just wouldn't work.
I discovered that the problem stemmed from not passing a userId parameter to the constructor of LogService. Interestingly, removing the userId requirement allowed the code to function properly, but that's not the ideal solution for me as it breaks other functionalities.
As a newcomer to Angular, I'm eager to learn how I can pass the userId while calling LogService in GlobalErrorHandler. Any insight or suggestions would be greatly appreciated. Thank you!
@Injectable({
providedIn: 'root'
})
export class LogService {
private logger!: Logger;
constructor(private userId: string) {}
}
The following snippet is where LogService is called from another file:
export class GlobalErrorHandler extends ErrorHandler {
constructor(private injector: Injector) {
super();
}
public handleError(error: any | HttpError | HttpErrorResponse ) {
const logService: LogService = this.injector.get(LogService); // The error occurs at this line and halts progress :(
const router: Router = this.injector.get(Router);
const message = error.message ? error.message : error.toString();
if (error.status) {
error = new Error(message);
}
}