Как правильно импортировать / вводить aurelia, чтобы использовать setRoot? - PullRequest
1 голос
/ 27 апреля 2019

Я пытаюсь настроить приложение с двумя «оболочками», один для входа в систему и один для приложения после аутентификации.Я следую приведенному здесь примеру, любезно предоставленному Мэтью Джеймсом Дэвисом, https://foursails.github.io/sentry, также показан в этом вопросе Как переключаться между страницей входа и приложением с помощью Aurelia .

Мой кодниже.Я получаю ошибку, показанную ниже.Я думаю, что я не использую импорт и внедрение {Aurelia} из 'aurelia-framework', но я не могу понять ошибку.

Любая помощь приветствуется.Благодарю.

В main.js

import {AuthService} from './auth-service';

export function configure(aurelia) {
  aurelia.use
    .standardConfiguration()
    .feature('resources');

  aurelia.use.developmentLogging(environment.debug ? 'debug' : 'warn');

  if (environment.testing) {
    aurelia.use.plugin('aurelia-testing');
  }


  aurelia.start().then(() => {
    var auth = aurelia.container.get(AuthService);
      let root = auth.isLoggedIn() ? 'app' : 'login';
    aurelia.setRoot(root);
  });
}

В login.js

import { inject, Aurelia } from 'aurelia-framework';
import {AuthService} from './auth-service';

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

    login(){
        this.auth.login();
        this.app.setRoot('app');
    }

}

В приложении.js

import { inject, Aurelia } from 'aurelia-framework';
import AuthService from 'auth-service';

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

  logout(){
    this.auth.logout();
    this.app.setRoot('login');
  }
}

В auth-service.js (пока просто макет)


 export class AuthService {



    constructor(){
        this.userLoggedIn = false;

    }

    login() {
        this.userLoggedIn = true;
    }

    logout(){
        this.userLoggedIn = false;
    }

    isLoggedIn(){
        return this.userLoggedIn;
    }

}

Когда я запускаю приложение, оно отображает «логин», как и ожидалось,У него есть кнопка, которая вызывает login ().Я ожидаю, что эта функция затем запустит this.app.setRoot ('app').Однако я получаю следующую ошибку:

aurelia-pal.js:37 Uncaught (in promise) Error: Error invoking App. Check the inner error for details.
------------------------------------------------
Inner Error:
Message: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
Inner Error Stack:
Error: key/value cannot be null or undefined. Are you trying to inject/register something that doesn't exist with DI?
    at validateKey (http://localhost:9000/scripts/vendor-bundle.js:54152:11)
    at Container.get (http://localhost:9000/scripts/vendor-bundle.js:54356:5)
    at Object.invoke (http://localhost:9000/scripts/vendor-bundle.js:54214:31)
    at InvocationHandler.invoke (http://localhost:9000/scripts/vendor-bundle.js:54172:166)
    at Container.invoke (http://localhost:9000/scripts/vendor-bundle.js:54443:23)
    at StrategyResolver.get (http://localhost:9000/scripts/vendor-bundle.js:53805:36)
    at Container.get (http://localhost:9000/scripts/vendor-bundle.js:54382:21)
    at http://localhost:9000/scripts/vendor-bundle.js:70122:71
End Inner Error Stack
------------------------------------------------

    at new AggregateError (http://localhost:9000/scripts/vendor-bundle.js:57264:11)
    at Container.invoke (http://localhost:9000/scripts/vendor-bundle.js:54445:13)
    at StrategyResolver.get (http://localhost:9000/scripts/vendor-bundle.js:53805:36)
    at Container.get (http://localhost:9000/scripts/vendor-bundle.js:54382:21)
    at http://localhost:9000/scripts/vendor-bundle.js:70122:71
AggregateError  @   aurelia-pal.js:37
invoke  @   aurelia-dependency-injection.js:692
get @   aurelia-dependency-injection.js:52
get @   aurelia-dependency-injection.js:629
(anonymous) @   aurelia-templating.js:4902
Promise.then (async)        
setRoot @   aurelia-framework.js:215
login   @   login.js:23
evaluate    @   aurelia-binding.js:1555
callSource  @   aurelia-binding.js:5275
handleEvent @   aurelia-binding.js:5284

1 Ответ

1 голос
/ 30 апреля 2019

Спасибо @bigopon, ваш совет привел к решению.Запись импорта для AuthService как:

import {AuthService} from './auth-service';

сработала.Я просмотрел соответствующий документ для импорта из MDN ссылка .Если в 'auth-service.js' я использовал

export default AuthService {...

, тогда

import AuthService from './auth-service;

будет работать.Однако я не понимаю, почему ошибка из строки в login.js

this.app.setRoot('app');

вызвала ошибку, а не предыдущую строку.Спасибо за вашу помощь!

...