Aurelia load routes dynamically / from fetch

前端 未结 4 1604
庸人自扰
庸人自扰 2020-12-18 16:13

I want to load menu options dynamically. so I\'m wondering the best approach

I am able to use the code below to add routes after the page is loaded. This works for n

4条回答
  •  清歌不尽
    2020-12-18 17:00

    You can add routes dynamically (at startup or anytime for that matter) by having a single fixed (static) route in the "configureRouter" method (in app.ts), to which you then add all the other routes dynamically, when your fetch completes, like so:

    configureRouter(config, router) {
        config.title = 'SM';
    
        //configure one static route:
        config.map([
            { route: ['', 'welcome'], name: 'welcome', moduleId: 'welcome/welcome', title: 'Welcome' } 
        ]);
    
        routeMaps(this.navRepo) //your repo/service doing the async HTTP fetch, returning a Promise> (i.e., the routes)
            .then(r => {
                r.forEach(route => this.router.addRoute(route));
                //once all dynamic routes are added, refresh navigation:
                this.router.refreshNavigation();
            });
    
        this.router = router;
    }
    

    The "routeMaps" function is just a wrapper around the repo call and a mapping of the result to the Array of route items.

提交回复
热议问题