繁体   English   中英

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的类,其中包含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();
    }
}

我一直在做类似的事情,但我发现在连接viewmodel时我不能依赖于在其他视图authcontext中填充的authcontext 返回由返回的承诺get ,然后返回next()的分辨率内get似乎解决了,这个想法是不进入下一个流水线步骤,直到这一个已经解决了。 将其应用于@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();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM