Angular2 get current route's alias

后端 未结 5 1890
情深已故
情深已故 2021-01-11 10:39

I\'m able to get current route\'s path like: /about, /, /news with location.path(). But how can I get its alias instead (the \'as\' part in the definition of a route)?

5条回答
  •  甜味超标
    2021-01-11 11:08

    If you know the list of possible aliases then it's possible to find out the name of the current alias using a combination of router.generate and route.isActiveRoute:

    For example, I have a wizard with three steps. I have a list of step aliases in an array:

    private wizardAliases = [
        'wizardStep1',
        'wizardStep2',
        'wizardStep3'
    ];
    

    I then use the following code to determine the current alias name:

    const alias = this.wizardAliases
        .map(alias => ({ alias, navigationInstruction: this.router.generate([alias]) }))
        .filter(x => this.router.isRouteActive(x.navigationInstruction))
        .map(x => x.alias);
    
    if (alias.length === 1) {
        console.log(`alias is ${alias}`);
    }
    

    Disclaimer: I haven't tried to see if this works with route parameters.

提交回复
热议问题