Aurelia路由器导航不起作用
问题描述:
我尝试实现自己的身份验证,并将令牌保存在sessionStorage中。 在每一页我检查:Aurelia路由器导航不起作用
attached() {
if (sessionStorage.getItem("token") == null) {
console.log("sessionStorage null");
this.theRouter.navigate("login");
}
console.log("continue on transactions");
....
}
至于结果 - 我在控制台中看到消息sessionStorage的空,但导航不工作,我看到消息继续交易也。
我在app.ts(主文件)的路线如下:
config.map([{
route: ['', 'home'], name: 'home', moduleId: PLATFORM.moduleName('../home/home'), nav: true, title: 'Home'
},{
route: 'transactions', name: 'transactions', moduleId: PLATFORM.moduleName('../transactions/transactions'), nav: true, title: 'Transactions'
}, {
route: 'login', name: 'login', moduleId: PLATFORM.moduleName('../auth/login'), nav: false, title: 'Login'
}]);
如何我可以组织正确的重定向?
在此先感谢。
答
我在猜测navigate
之后的return
声明应该会停止函数的执行。
话虽这么说...
你应该看看使用路由器管道挂钩这样做是为了减少重复代码:http://aurelia.io/hub.html#/doc/article/aurelia/router/latest/router-configuration/8
下面直接是从该链接的例子:
import {Redirect} from 'aurelia-router';
export class App {
configureRouter(config, router) {
var step = new AuthorizeStep;
config.addAuthorizeStep(step)
config.map([
{ route: ['', 'home'], name: 'home', moduleId: 'home/index' },
{ route: 'users', name: 'users', moduleId: 'users/index', settings: { auth: true } },
{ route: 'users/:id/detail', name: 'userDetail', moduleId: 'users/detail', settings: { auth: true } },
{ route: 'files/*path', name: 'files', moduleId: 'files/index', href:'#files', nav: true }
]);
}
}
class AuthorizeStep {
run(navigationInstruction, next) {
if (navigationInstruction.getAllInstructions().some(i => i.config.settings.auth)) {
var isLoggedIn = // insert magic here;
if (!isLoggedIn) {
return next.cancel(new Redirect('login'));
}
}
return next();
}
}
谢谢为您的解决方案。 不幸的是,我在课后添加了AuthorizeStep后重复了我的问题。 我已经通过遵循标准决定解决了这个问题 - 我为每条必要的路线添加了_auth = true_。 –