Aurelia:在路由器的管道步骤中,如何将变量绑定到该路由器?

时间:2015-07-15 08:23:00

标签: javascript aurelia aurelia-binding aurelia-navigation aurelia-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();
    }
}

1 个答案:

答案 0 :(得分:4)

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

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