0

I have an angular service that is just supposed to monitor for route changed events. When I try to add this service at the AppModule level I get a compilation error that says something like "Service is declared but its value is never read'. I understand what the error means and get why its popping up, the issue is that I don't need to call any of the service functions from outside the service. Here is a snippet similar to what I have going on for my Service

@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) {
    // do some stuff with the page name
  }
}

This is what I have in my app.module.ts. If I don't include the ngOnInit function that just does a console log with my service then it will fail to compile.

export class AppModule {
  constructor(
    private myService: MyService // if this line is not here then my service doesn't load at all and the route changed event is not tracked
  ) { }

  ngOnInit() {
    console.log(this.myService);
  }
}

If I do the console.log I can see the route changed event firing so I know the service gets loaded. Is it possible to do include the MyService reference without requiring the console.log?

Sébastien
  • 11,860
  • 11
  • 58
  • 78

1 Answers1

0

You said it works, but I can't see how. You are not subscribing to the route events. Something like this makes more sense to me:

this.router.events
  .filter(e => e instanceof NavigationEnd)
  .map(e => this.route.root.firstChild.snapshot.data.analytics.pageName)
  .subscribe(this.onRouteChanged)

This other code is necessary to angular creates an instance of your service

constructor(
    private myService: MyService
  ) { }

I just tried a test here and I didn't need this console.log(this.myService) for it to work. Maybe if you provide more information.

Leandro Lima
  • 1,164
  • 6
  • 12
  • I'm pretty new to Angular 4 so not quite sure how its working. I am inheriting this app from another team and I can't post the exact source code here. I will try to make an sample app that shows the issue. Do you know if its possible to have that "private myService: MyService" in the code without having to reference any of the service functions? – Steven Garcia Jan 23 '18 at 02:37
  • I did some more research and noticed in the first answer of this post I linked does it the same way as my code https://stackoverflow.com/questions/33520043/how-to-detect-a-route-change-in-angular – Steven Garcia Jan 23 '18 at 02:59