How to access child router in Aurelia?

大城市里の小女人 提交于 2019-12-20 15:30:57

问题


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

Below line of code gives the parent router instance.

import {Router} from 'aurelia-router'

How to get child router instance?


回答1:


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

import { Router } from 'aurelia-router';

class ChildViewModel() {  
    configureRouter(config, router) {
        this.router = router;
        // router config
    }
    someOtherFunction() {
        this.router.navigate('somewhere');
    }
}

If you then want to use the child router in another view model, you can import it and use the router on the class (assuming that the class is a singleton, which it should be unless you configure it otherwise).

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');
    }
}



回答2:


My friend helped me solve this. For the child router on first router navigation I had blank '' and it took the URL with like localhost:9000/. When I try to navigate from there I had problem. So from the first navigation, I changed to the code to route like childrouter/name and it worked.



来源:https://stackoverflow.com/questions/31712517/how-to-access-child-router-in-aurelia

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!