我意识到这有点像线程死灵法,但我想添加一个答案,因为接受的答案提供了 Aurelia 文档明确建议反对的解决方案(您必须向下滚动到该方法。reset()
在我意识到自己看错之前,我尝试了其他几种方法,取得了不同程度的成功。路由限制是应用程序关心的问题,因此使用 AuthorizeStep 方法绝对是阻止某人进入给定路由的方法。不过,在我看来,过滤掉用户在导航栏上看到的路线是一个视图模型问题。不过,我并不真的觉得它是像 @MickJuice 那样的值转换器,因为我看到的每个示例都是关于格式化,而不是过滤,而且我觉得将它放在导航栏视图模型。我的方法如下:
// app.js
import AuthenticationService from './services/authentication';
import { inject } from 'aurelia-framework';
import { Redirect } from 'aurelia-router';
@inject(AuthenticationService)
export class App {
constructor(auth) {
this.auth = auth;
}
configureRouter(config, router) {
config.title = 'RPSLS';
const step = new AuthenticatedStep(this.auth);
config.addAuthorizeStep(step);
config.map([
{ route: ['', 'welcome'], name: 'welcome', moduleId: './welcome', nav: true, title: 'Welcome' },
{ route: 'teams', name: 'teams', moduleId: './my-teams', nav: true, title: 'Teams', settings: { auth: true } },
{ route: 'login', name: 'login', moduleId: './login', nav: false, title: 'Login' },
]);
this.router = router;
}
}
class AuthenticatedStep {
constructor(auth) {
this.auth = auth;
}
run(navigationInstruction, next) {
if (navigationInstruction.getAllInstructions().some(i => i.config.settings.auth)) {
if (!this.auth.currentUser) {
return next.cancel(new Redirect('login'));
}
}
return next();
}
}
好的,这样如果用户没有登录,它本身就会限制用户对路由的访问。我可以很容易地将它扩展到基于角色的东西,但我现在不需要。然后 nav-bar.html 就在骨架之外,而不是直接在nav-bar.html
我创建的路由器中绑定路由器nav-bar.js
以使用完整的视图模型,如下所示:
import { inject, bindable } from 'aurelia-framework';
import AuthenticationService from './services/authentication';
@inject(AuthenticationService)
export class NavBar {
@bindable router = null;
constructor(auth) {
this.auth = auth;
}
get routes() {
if (this.auth.currentUser) {
return this.router.navigation;
}
return this.router.navigation.filter(r => !r.settings.auth);
}
}
而不是router.navigation
在这一点上迭代,nav-bar.html
将迭代routes
我上面声明的属性:
<ul class="nav navbar-nav">
<li repeat.for="row of routes" class="${row.isActive ? 'active' : ''}">
<a data-toggle="collapse" data-target="#skeleton-navigation-navbar-collapse.in" href.bind="row.href">${row.title}</a>
</li>
</ul>
同样,您的里程可能会有所不同,但我想发布此内容,因为我认为这是针对常见要求的相当干净且无痛的解决方案。