Sorry, but I’m having a hard time making any sense out of this post, so I’ll try just rephrasing my concern.
Any code - including a backbutton handler - that needs to behave differently depending on what page is currently being interacted with, can be implemented in two ways.
Option A: have one single handler function with a big if/else switch cascade. If we’re on page A, do A. If we’re on page B, do B. If we’re on page C, do C. This is what I understand you’re advocating.
Option B: have one handler function per page. Register the page A handler (that does A) when page A becomes current, using lifecycle events to know when that happens. Deregister the page A handler when that page leaves. Register the page B handler (that does B) when page B becomes current, and so on.
I prefer option B for three reasons:
- It makes for smaller functions. Smaller functions are easier to read and understand.
- If/else and switch/case are notorious sources of bugs, because things fall through the cracks in ways that aren’t easily visible. I call this “negative space code”, where you have to understand both what is happening and what isn’t happening.
- All code specific to page X should be in
x.page.ts, to the extent humanly possible. That way, when we get a bug report about page X, we know exactly where to start looking. Also, when somebody looking to change how page X works, they know everywhere they have to pay attention to. If the back button handler is in
app.component.ts, that’s not obvious to me when I rearchitect the router URLs because somebody in marketing wants “prettier” URLs or now the back button should do C when the user’s on page A, instead of A like it used to.
So, in conclusion, I don’t like the smell of back button handlers that query the router for state, because it means that they’re monolithic functions trying to affect the behavior of distant parts of the app, and that smells like spaghetti to me.