【问题标题】:Aurelia - Dynamic redirect in a child routeAurelia - 子路由中的动态重定向
【发布时间】:2017-01-16 03:16:44
【问题描述】:

我有一个 Aurelia 应用程序,即父子路由器。家长:

{ name: 'group', route: 'group/:groupId', viewPorts: {
    Filter: { moduleId: 'filter.js'},
    Content: { moduleId: 'content.js' }
}}

子路由器设置完毕:

[
    { name: 'home',      route: ''          },
    { name: 'documents', route: 'documents' },
    { name: 'images',    route: 'images'    },
    { name: 'specs',     route: 'specs'     }
]

子路由器在content.js 中配置。我想实现,在父路由器中,我在没有指定子完整路径的情况下导航

router.navigateToRoute('group', { groupId: 12345 });

在子路由器中,这将在home 结束,我将在其中根据某些应用程序状态执行动态重定向。应该如何实现?到目前为止,我已经尝试过这些

RedirectToRoute:

activate(params: any, config: any, instruction: NavigationInstruction): any {
    return new RedirectToRoute('pick one child route');
}

注入Router:

@inject(Router)
export class Home {
    constructor(router: Router) {
        this.router = router;
    }
    activate(params: any, config: any, instruction: NavigationInstruction): void {
        this.router.navigateToRoute('pick one child route');
    }
}

重定向/导航本身是正确的本地,但是(子)路由器的baseUrl 仍然指向旧的(父)路由,所以结果会不正确。 p>

例如:我们在一个页面上:group/98765/images,在父路由器中,我们导航:router.navigateToRoute('group', { groupId: 12345 });。正如预期的那样,我们最终会得到group/12345homeactivate 方法。

我们重定向到这里,比如说specs。但是,由于 baseUrl 已过时,我们最终将使用 group/98765/specs,而不是 group/12345/specs

应该如何解决?

我已经看到子路由器baseUrl 的一些相关问题,建议在导航之前手动修复 为常量。但是,由于模板化路由(比本示例中显示的更复杂),这并不像将 baseUrl 设置为常量字符串那么简单。

【问题讨论】:

标签: aurelia


【解决方案1】:

虽然路由器事件会起作用,但它并不优雅,因为会发生两次导航并出现在浏览器历史记录中。如果用户试图向后导航,他/她不能,因为导航回到home 路线,这将立即向前导航到选定的子路线。

“正确”的方式(在 Aurelia 文档中):在配置路由器时使用 navigationStrategy 回调。所以这是设置子路由器的方法:

configureRouter(config: RouterConfiguration, router: Router) {
    const navStrat = (instruction: NavigationInstruction) => {
        instruction.config.redirect = 'pick one child route';
    };
    config.map([
        { name: 'redirecter', route: '',         navigationStrategy: navStrat },
        { name: 'documents',  route: 'documents'                              },
        { name: 'images',     route: 'images'                                 },
        { name: 'specs',      route: 'specs'                                  }    
    ]);
}

这将导致一个导航循环,并且可以实现任何动态重定向逻辑。

【讨论】:

  • 注意,AppRouter(顶级路由器)发送EventAggrerator事件,例如'router:navigation:success'。这不是最好的解决方案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 1970-01-01
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多