Reputation: 518
I'm developing an Angular2 based quiz with a few 'static' components (home, faq, etc) and a component that represents the quiz cards. My setup uses a route with a placeholder just like this:
{
path: 'quiz/:questionPage',
component: QuizComponent
},
Here questionPage
is supposed to be numeric...
And to switch quiz cards I'm changing the location and show the new card:
import { Location } from '@angular/common';
import { ActivatedRoute } from '@angular/router'
...
constructor (
private route: ActivatedRoute,
private location: Location) {...}
...
showQuestion(next) {
this.location.go ('quiz/' + next);
this.showQuestion (next);
}
To implement browser back/forward in the QuizComponent
(besides the next/prev in the quiz cards) I thought I could just just subscribe to the route's parameter in the QuizComponent
's constructor:
this.route.params.subscribe(params => {
console.log ("found params: ", params);
});
That's been working like a charm: clicking next/prev updated the cards and with the browsers back/forward I am able to go through the history of cards. All perfect I thought, but I just discovered that there is at least one use case that does not work:
If I go back (no matter how often) and then click something new the back button does only update the location (url in addressbar) but the above subscription is not fired (and thus the card won't get updated). If I click back one more time it's working fine again, but I'm then 2 steps back!? I can go forward again to access the correct entry in the history, but that's of course annoying...
So.. Am I doing something wrong? Maybe that's also a super-stupid approach to implement browser-back/forward?
Upvotes: 2
Views: 903
Reputation: 12572
Actually, after reading the documentation for Location I assume this is indeed the problem. This is a service for interacting with the browsers URL, you should use the Router for navigation inside your apps.
As stated in the documentation also:
Use Location only if you need to interact with or create normalized URLs outside of routing.
So if you navigate with something like:
this.router.navigate(['quiz', next]);
it should work as expected.
Upvotes: 1