Aurelia:在路由器的流水线步骤中,我如何将变量绑定到该路由器?

Aurelia: During a Router's Pipeline Step, how do I bind a variable to that router?

我想将在 AuthorizeStep 期间找到的用户传递给 App class,然后再传递给 home module

这是我的资料:

export class App {
    configureRouter(config, router) {
        config.addPipelineStep('authorize', AuthorizeStep); 
        config.map([
            {route: ['', ':filter'], name: "", moduleId: 'welcome'}
            {route: 'home', name: "home", moduleId: 'home' auth:true}
        ]);
        this.router = router;
    }
}

class AuthorizeStep {
    run(routingContext, next) {
        if (routingContext.nextInstructions.some(i => i.config.auth)) {
            this.client.get('auth/login')
                .then(response => {
                    this.user = response.content;
                });
        }
        return next();
    }
}

在我的应用程序中,我创建了一个名为 AuthContext 的 class with currentUser 属性。您可以将它注入到 AuthorizeStep 的构造函数中,然后将它注入到任何其他需要它的模型中。像...

import {AuthContext} from './auth-context';

export class App {
    static inject() { return [AuthContext];}

    constructor(authcontext){
        this.authContext = authcontext;
    }

    configureRouter(config, router) {
         config.addPipelineStep('authorize', AuthorizeStep); 
         config.map([
            {route: ['', ':filter'], name: "", moduleId: 'welcome'}
            {route: 'home', name: "home", moduleId: 'home' auth:true}
        ]);
        this.router = router;
    }
}

class AuthorizeStep {
    static inject() { return [AuthContext];}

    constructor(authcontext){
        this.authContext = authcontext;
    }
    run(routingContext, next) {
        if (routingContext.nextInstructions.some(i => i.config.auth)) {
            this.client.get('auth/login')
                .then(response => {
                    this.authcontext.user = response.content;
                });
        }
        return next();
    }
}

我一直在做类似的事情,但我发现我不能依赖 authcontext 在附加视图模型时填充到其他视图模型中。返回 get 返回的承诺,然后在 get 的解决方案内返回 next() 似乎解决了这个问题,这个想法是在解决这个问题之前不继续进行下一个管道步骤.将其应用于@JamesCarters 的 ,我会得到以下(未经测试的)代码:

class AuthorizeStep {
    static inject() { return [AuthContext];}

    constructor(authcontext){
        this.authContext = authcontext;
    }
    run(routingContext, next) {
        if (routingContext.nextInstructions.some(i => i.config.auth)) {
            return this.client.get('auth/login')
                .then(response => {
                    this.authcontext.user = response.content;
                    return next();
                });
        }
        else {
            return next();
        }
    }
}