Trying to implement an Angular service to monitor route changed events has led to a compilation error at the AppModule level. The error message indicates "Service is declared but its value is never read", which I understand and acknowledge. The challenge lies in not needing to call any of the service functions externally. Below is a snippet resembling my Service implementation:
@Injectable()
export class MyService {
constructor(
private router: Router,
private route: ActivatedRoute
) {
this.router.events
.filter(e => e instanceof NavigationEnd)
.forEach(e => this.onRouteChanged(this.route.root.firstChild.snapshot.data.analytics.pageName));
}
onRouteChanged(pageName: string) {
// perform operations with the page name
}
}
In my app.module.ts, including the ngOnInit function that simply logs my service prevents compilation errors like so:
export class AppModule {
constructor(
private myService: MyService // necessary for service to load and track route changes
) { }
ngOnInit() {
console.log(this.myService);
}
}
The console.log confirms the firing of route changed events, ensuring that the service is loaded successfully. Is there a way to include the MyService reference without relying on the console.log statement?