How to switch between login page and app with Aurelia

前端 未结 2 934
误落风尘
误落风尘 2020-12-05 10:40

I\'m using the Aurelia skeleton for my project. Everything seemed so intuitive, however I\'m stuck with a problem which I suspect is fairly easy (if you know how).

T

相关标签:
2条回答
  • 2020-12-05 11:22

    For a working example of setRoot you can check also https://foursails.github.io/sentry https://github.com/foursails/sentry

    0 讨论(0)
  • 2020-12-05 11:31

    I think aurelia's setRoot(module) function will help with this.

    Here's the standard main.js file that "bootstraps" the aurelia app:

    main.js

    export function configure(aurelia) {
      aurelia.use
        .standardConfiguration()
        .developmentLogging();
    
      aurelia.start()
        .then(a => a.setRoot()); // this is the equivalent of setRoot('app')
    }
    

    When setRoot is called with no arguments Aurelia looks for an app.js + app.html viewmodel and view.

    We can adjust the logic to check whether the user is logged in and if not, show the login screen:

    main.js

    export function configure(aurelia) {
      aurelia.use
        .standardConfiguration()
        .developmentLogging();
    
      aurelia.start()
        .then(a => {
          if (userIsLoggedIn()) {
            a.setRoot('app');
          } else {
            a.setRoot('login');
          }
        });
    }
    

    Then in your login view model you can call setRoot('app') after the user has successfully logged in:

    login.js

    import {Aurelia, inject} from 'aurelia-framework';
    import {AuthService} from './my-auth-service';
    
    @inject(Aurelia, AuthService)
    export class Login {
      userName = '';
      password = '';
    
      constructor(aurelia, authService) {
        this.aurelia = aurelia;
        this.authService = authService;
      }
    
      submit() {
        // attempt to login and if successful, launch the app view model.
        this.authService.login(userName, password)
          .then(() => this.aurelia.setRoot('app'));
      }
    }
    

    Note: if your app includes a "logout" feature that will send the user back to the login screen (eg setRoot('login')), be sure to reset the router and update the url accordingly. This will prevent issues when the user signs back in. More details in here and here.

    0 讨论(0)
提交回复
热议问题