Reputation: 45
I am trying to generate some routes dynamically in a child router basing on a parameter provided within the url.
So I have my main router configured with that route : mydomain.com/#/page/:page that is loading a module "page"
And in my module page I have a configureRouter function which is supposed to fetch the sections relative to the page specified in the url before to add them in the child router:
public async configureRouter(config, router){
page = ???
sections = wait fetchPageSections(page)
//for each section, add route in child router
}
My problem here is how to retrieve the :page parameter, since this will be available only (if I understand well) in the activate() function, that will be called after configureRouter(). However, since that part of the route has already been "matched" in the parent router, I think there should be a way to retrieve it in the configureRouter function.
Thanks.
Upvotes: 0
Views: 790
Reputation: 10887
The router you are passed in configureRouter(config, router)
is the child router. Luckily, it has a parent
property that will provide you with what you want.
router.parent.currentInstruction.params.page
should give you what you're looking for: the page
parameter from the parent router.
Upvotes: 1
Reputation: 11990
I don't know if there is a way to retrieve the :page
parameter in the configureRouter()
method, because as far as I know, at this point the new route has not been triggered yet.
You can retrieve the :page
parameter in the created()
method.
created() {
let page = this.router.parentInstruction.params.page;
// do something and add routes
//this.router.addRoute({ route: "test", moduleId: "test", nav: true, title: "test" });
//this.router.refreshNavigation();
}
A second option would be using a global object to hold the desired parameter. You could inject this object in the constructor()
method of the view component. However, this would be an overkill and unsafe to use. I do not think it is a good idea.
A third option, and the easiest one in my opinion, is using mapUnknownRoutes()
for dynamic routes:
router.configure(config => {
config.mapUnknownRoutes(instruction => {
//read the instruction.fragment to get
//you can return a promise and make async requests
return instruction;
});
});
I hope this helps!
Upvotes: 1