How to access a child router in Aurelia?

I have two child routers. I can move from one to another. But from the view of the child router, how can I navigate?

An instance of the parent router is issued below the line of code.

import {Router} from 'aurelia-router'

How to get an instance of a child router?

+3
source share
2 answers

To create a child router, create a new router on the child route in the same way as you created the router on the parent route. Then set the router as a property of the view model class so that you can access it throughout the view model.

 import { Router } from 'aurelia-router'; class ChildViewModel() { configureRouter(config, router) { this.router = router; // router config } someOtherFunction() { this.router.navigate('somewhere'); } } 

If you want to use the child router in a different view model, you can import it and use the router in the class (assuming the class is singleton, which it should be, unless you configured it differently).

 import { inject } from 'aurelia-framework'; import { ChildViewModel } from './child-view-model'; @inject(ChildViewModel) class AnotherViewModel() { constructor(cvm) { this.externalRouter = cvm.router; } doStuff() { this.externalRouter.navigate('somewhere'); } doOtherStuff() { ChildViewModel.router.navigate('somewhere else'); } } 
+4
source

My friend helped me solve this problem. For the child router, when I first navigated the router, I had an empty one '', and it received the URL with localhost: 9000 /. When I try to go from there, I have a problem. So from the first navigation, I switched to routing code like childrouter / name, and it worked.

0
source

All Articles