tl;dr-我如何延迟aurelia-router.js
中的processResult()
函数的执行,因为我仍然在等待代码中的承诺的结果?它会导致正确的模块呈现,但地址不正确/href。
示例:如果您在base-module,然后单击admin,admin模块将加载,但href
仍然是www.mycompany.com/#/base-module
而不是www.mycompany.com/#/admin
,并且可以在控制台中看到此错误:
错误[app-router]错误:预期路由器管道返回导航结果,但得到的是[{}]
较长版本:
我的路由器中有一个预置步骤,在呈现视图之前检查用户是否启用了特定模块。
在我的PreRenderStep类中,我有一个run函数,它调用一个中介来获取用户的权限,然后检查用户单击的模块是否在他们的enabled modules列表中。对调解人的呼吁涉及一个承诺。
问题是prerender步骤中的run承诺会在run方法中的承诺完成之前解决。因此,视图最终会呈现(因为启用了用户),但前面的href仍保留在地址栏中。
路由器:
null
configureRouter(config, router) {
config.title = "Tramonex";
config.addPipelineStep('authorize', AuthorizeStep);
config.addPreRenderStep(PreRenderStep);
config.map([
{
route: ['', 'log-in-out'],
name: 'home',
moduleId: 'modules/authentication/log-in-out'
},
{
route: 'passwordReset',
moduleId: 'modules/authentication/password-reset',
},
{route: 'app', moduleId: 'app', auth: true},
{
route: 'base-module',
name: 'base-module',
moduleId: 'modules/base-module',
href: 'base-module',
nav: true,
auth: true
},
{
route: 'test1',
name: 'test1',
moduleId: 'modules/test1/test1',
href: 'test1',
nav: true,
auth: true,
settings: {moduleAuthRequired: true}
},
{
route: 'test2',
name: 'test2',
moduleId: 'modules/test2/test2',
href: 'test2',
nav: true,
auth: true,
settings: {moduleAuthRequired: true}
},
{
route: 'admin',
name: 'admin',
moduleId: 'modules/admin/admin',
href: 'admin',
nav: true,
auth: true,
settings: {moduleAuthRequired: true}
},
]);
this.router = router;
}
}
null
PreRenderStep:
null
@inject(Mediator, AuthenticationService)
class PreRenderStep {
constructor(mediator, authenticationService) {
this.mediator = mediator;
this.authenticationService = authenticationService;
}
run(navigationInstruction, next) {
if (navigationInstruction.getAllInstructions().some(i => i.config.settings.moduleAuthRequired)) {
this.redirect = false;
this.mediator.getPermissionsForUser()
.then(user => {
userPerms = user.modules;
var isEnabled = userPerms.includes(navigationInstruction.config.name);
if (!isEnabled) {
this.redirect = true;
}
})
.then(() => {
return this.redirect next.cancel(navigationInstruction.router.navigateToRoute('base-module')) : next();
});
}
else {
return next();
}
}
}
null
当用户单击一个需要验证检查的模块时,就会命中代码,而当我们等待Mediator.getPermissionsForUser()的承诺返回时,就会命中aurelia-router.js中的代码(带星号的行):
null
function processResult(instruction, result, instructionCount, router) {
if (!(result && 'completed' in result && 'output' in result)) {
result = result || {};
**result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.');**
}
var finalResult = null;
if (isNavigationCommand(result.output)) {
result.output.navigate(router);
} else {
finalResult = result;
if (!result.completed) {
if (result.output instanceof Error) {
logger.error(result.output);
}
**restorePreviousLocation(router);**
}
}
null
您需要返回在run函数中创建的承诺。
return this.mediator.getPermissionsForUser()