Роутер Aurelia не работает при сбросе рута

Я хочу использовать aurelia-auth в своем приложении, а также иметь страницу входа, которая полностью отделена от остальной части приложения. Я следовал учебному пособию по этой ссылке: https://auth0.com/blog/2015/08/05/creating-your-first-aurelia-app-from-authentication-to-calling-an-api/

Проблема, с которой я столкнулся, заключается в том, что после успешного входа в систему и попытки перенаправить приложение, ни один из маршрутов не найден Я получаю маршрут не найден независимо от того, что я вставил для URL перенаправления входа в систему.

Вот мой код:

app.js:

...
import { Router } from 'aurelia-router';
import { AppRouterConfig } from './router-config';
import { FetchConfig } from 'aurelia-auth';

...

@inject(..., Router,   AppRouterConfig, FetchConfig)
export class App {
    constructor(router, appRouterConfig, FetchConfig) {
        this.router = router;
        this.appRouterConfig = appRouterConfig;
        this.fetchConfig = fetchConfig;

        ...
    }

    activate() {
         this.fetchConfig.configure();
         this.appRouterConfig.configure();
    }

    ...

}

login.js:

import { AuthService } from 'aurelia-auth';
import { Aurelia } from 'aurelia-framework';
...

@inject(..., Aurelia, AuthService)
export class LoginScreen {
    constructor(..., aurelia, authService) {
         this.aurelia = aurelia;
         this.authService = authService;
         ...
    }

    login() {
        return this.authService.login(this.username, this.password)
            .then(response => {
                console.log("Login response: " + response);
                this.aurelia.setRoot('app');
             })
             .catch(error => {
                this.loginError = error.response;
                alert('login error = ' + error.response);
             });
    }

    ...

}

main.js:

import config from './auth-config';
import { AuthService } from 'aurelia-auth';
import { Aurelia } from 'aurelia-framework';
...

export function configure(aurelia) {
    aurelia.use
       .defaultBindingLanguage()
       .defaultResources()
       .developmentLogging()
       .router()
       .history()
       .eventAggregator()
       ...
       .plugin('aurelia-auth', (baseConfig) => {
           baseConfig.configure(config);
       });


    let authService = aurelia.container.get(AuthService);
    aurelia.start()
        .then(a => {
           if (authService.isAuthenticated()) {
              a.setRoot('app');
           } else {
              a.setRoot('login');
           }
        });
}

Auth-config.js:

var config = {
    baseUrl: 'http://localhost:3001',
    loginUrl: 'sessions/create',
    tokenName: 'id_token',
    //loginRedirect: '#/home' //looks like aurelia-auth defaults to #/ which is fine for me
}

export default config;

маршрутизатор-config.js:

import { AuthorizeStep } from 'aurelia-auth';
import { inject } from 'aurelia-framework';
import { Router } from 'aurelia-router';

@inject(Router)
export class AppRouterConfig {
    constructor(router) {
        this.router = router;
    }

    configure() {
         console.log('about to configure router');

         var appRouterConfig = function (config) {
             config.title = 'My App';

             config.addPipelineStep('authorize', AuthorizeStep);

             config.map([
                {
                    route: ['', 'home'],
                    name: 'home',
                    moduleId: '.components/home/home',
                    nav: true,
                    title: 'Home',
                    auth: true
                },
                {
                    route: ['employees'],
                    name: 'employees',
                    moduleId: './components/employees/employees',
                    nav: true,
                    title: 'Employees',
                    auth: true
                }
             ]);

             this.router.configure(appRouterConfig);
        }
    };
}

При загрузке приложения оно успешно переходит на страницу входа, и я могу успешно войти в систему и пытается перенаправить, но я получаю эту ошибку в консоли:

ERROR [app-router] Error: Route not found: /
    at AppRouter._createNavigationInstruction (http://127.0.0.1:8080/jspm_packages/npm/aurelia-router@1.0.0-rc.1.0.1/aurelia-router.js:1039:29)
    at AppRouter.loadUrl (http://127.0.0.1:8080/jspm_packages/npm/aurelia-router@1.0.0-rc.1.0.1/aurelia-router.js:1634:19)
    at BrowserHistory._loadUrl (http://127.0.0.1:8080/jspm_packages/npm/aurelia-history-browser@1.0.0-rc.1.0.0/aurelia-history-browser.js:301:55)
    at BrowserHistory.activate (http://127.0.0.1:8080/jspm_packages/npm/aurelia-history-browser@1.0.0-rc.1.0.0/aurelia-history-browser.js:200:21)
    at AppRouter.activate (http://127.0.0.1:8080/jspm_packages/npm/aurelia-router@1.0.0-rc.1.0.1/aurelia-router.js:1689:20)
    at eval (http://127.0.0.1:8080/jspm_packages/npm/aurelia-router@1.0.0-rc.1.0.1/aurelia-router.js:1670:21)
    at AppRouter.registerViewPort (http://127.0.0.1:8080/jspm_packages/npm/aurelia-router@1.0.0-rc.1.0.1/aurelia-router.js:1672:10)
    at new RouterView (http://127.0.0.1:8080/jspm_packages/npm/aurelia-templating-router@1.0.0-rc.1.0.1/router-view.js:112:19)
    at Object.invokeWithDynamicDependencies (http://127.0.0.1:8080/jspm_packages/npm/aurelia-dependency-injection@1.0.0-rc.1.0.1/aurelia-dependency-injection.js:329:20)
    at InvocationHandler.invoke (http://127.0.0.1:8080/jspm_packages/npm/aurelia-dependency-injection@1.0.0-rc.1.0.1/aurelia-dependency-injection.js:311:168)error @ aurelia-logging-console.js:54log @ aurelia-logging.js:37error @ aurelia-logging.js:70(anonymous function) @ aurelia-router.js:1637
aurelia-logging-console.js:54 ERROR [app-router] Router navigation failed, and no previous location could be restored.

Я довольно много гуглюсь, чтобы найти ответы на эти вопросы, но мне трудно найти хорошие ответы. У кого-нибудь есть идеи? Любая помощь приветствуется!

2 ответа

Решение

Я думаю, проблема в том, что вы настраиваете маршрутизатор внутри activate() метод. На мой взгляд, в этом нет необходимости.

Вы можете перейти к маршруту после сброса корневого компонента:

this.aurelia.setRoot('./login')
  .then((aurelia) => {
    aurelia.root.viewModel.router.navigateToRoute('someLoginRoute');
  });

Вы также можете использовать mapUnknownRoutes, что очень полезно:

configureRouter(config, router) {
      config.title = "Super Secret Project";
      config.map([
          { route: [ '', 'screen-1'], moduleId: "./screen-1", nav: true, title: "Beginscherm" },
          { route: 'screen-2', name:'screen-2', moduleId: "./screen-2", nav: true, title: "Beginscherm" }
      ]);

      config.mapUnknownRoutes(instruction => {
        return './screen-1';
      });

      this.router = router;        
  }

Посмотрите этот пример https://gist.run/?id=00b8b3745a480fb04184e8440e8be8c5. Обратите внимание на функции входа / выхода.

Надеюсь, это поможет!

Вы можете решить эту проблему, перезагрузив или обновив приложение. после настройки приложения т.е. a.setRoot('приложение'); location.reload();

Другие вопросы по тегам