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

蓝咒 提交于 2019-11-29 07:20:28

In my app I created a class called AuthContext with currentUser property. You can inject it in the constructor for the AuthorizeStep and then inject it in any other models that need it. Something like...

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

I have been doing something similar, but I found that I can't rely on the authcontext being populated in other viewmodels by the time the viewmodel is being attached. Returning the promise returned by the get and then returning next() within the resolution of the get seems to solve that, the idea being to not proceed to the next pipeline step until this one has resolved. Applying that to the answer from @JamesCarters, I'd get the following (untested) code:

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();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!