Aurelia 路由器的导航不起作用

Navigation for Aurelia router doesn't work

我尝试实现自己的身份验证,并将令牌保存在 sessionStorage 中。 在每一页上我检查:

 attached() {

        if (sessionStorage.getItem("token") == null) {
            console.log("sessionStorage null");
            this.theRouter.navigate("login");
        }
        console.log("continue on transactions");
....
}

结果 - 我在控制台中看到消息 sessionStorage null,但导航不起作用,我看到消息 continue on transactions 还有。

我在 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

下面是直接来自 link 的示例:

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();
  }
}