Angular 2 Routing Error - Exposed

05-03-2017
posts

I was recently doing some refactoring of some existing routes in my current Angular 2 project. I had split some services up for better maintainability. As I tested I kept running into the same behavior when I tried to navigate from one component to another. The Angular router would send me back to the default path: '' route every time.

1
this.router.navigate([`detail/${id}`]);

“Nope, can’t go there.”

Problem:

The problem was that detail was importing another service, my import statement had a typo. I received no feedback in the browser console or the terminal as to what error occurred, all I knew was that when I tried to navigate I ended up in a weird place with no information to start debugging.

Solution:

Adding a Angular router event listener to the main app-component allowed me to console log everything that was happening within the router.

1
2
3
this.router.events.subscribe((event) => {
console.log(event);
});

This returned all router events along with an error, cannot import user.Service.ts, not known. The error was because of a simple typo, user.Service.ts, but the compiler nor any other tooling gave me any indication of what was happening. Because I knew it was related to something that happened when I tried to change routes I exposed all of the router events to start to pinpoint where the reroute was failing. This simple addition at the top app-component level exposed the issue right away.