首页 文章

Angular2获取当前路由的别名

提问于
浏览
13

我能够获得当前路径的路径,例如:/ about,/,/ news with location.path() . 但是我怎样才能得到它的别名(路由定义中的'as'部分)?

{ path: '/about', as: 'About', component: About }

可能吗?

5 回答

  • 1

    NOTE: The following has been tested with the 2.0 beta series. The RC versions have an updated router component with breaking changes. The old one has been renamed to router-deprecated. This has not been tested yet against the new router.

    以下内容将根据您的有效路线打印 FooBar .

    @Component({
        selector: 'app',
        templateUrl: 'app/app.html',
        directives: [ROUTER_DIRECTIVES]
    })
    @RouteConfig([
      {path:'/', name: 'Foo', component: FooComponent, useAsDefault: true},
      {path:'/bar', name: 'Bar', component: BarComponent, useAsDefault: false},
    ])
    export class AppComponent implements OnInit {
        constructor(private _router: Router) {
        }
    
        ngOnInit() {
            console.log('current route name', 
                        this._router.currentInstruction.component.routeName);
        }
    }
    
  • 2

    无法看到获取它的方法,但另一种方法是使用RouteData传递路由的别名

    https://angular.io/docs/ts/latest/api/router/RouteData-class.html

  • 3

    您不应该使用位置,而应使用路由器实例 .

    在组件中,将其注入构造函数中:

    constructor(public router: Router)
    

    比,你可以获得组件的名称:

    this.router.currentInstruction.component.routeName
    

    我不确定你是如何从路由器配置获得 as 的 . 但是,RouterLink指令应该是正确的开始:https://angular.io/docs/ts/latest/api/router/RouterLink-directive.html

  • 2

    For >= Angular2 RC.x (new router)

    新路由器中不再有别名 .

    您可以获取本地组件的相对路径

    routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
        console.log(curr.stringifiedUrlSegments);
      }
    

    或使用的完整路径

    constructor(private router:Router) {}
    
      routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void {
        console.log(this.router.serializeUrl(tree));
      }
    

    要么

    constructor(router:Router, private location:Location) {
      router.changes.subscribe(() => {
        console.log(this.location.path());
      });
    }
    
  • 0

    如果您知道可能的别名列表,那么可以使用 router.generateroute.isActiveRoute 的组合找出当前别名的名称:

    例如,我有一个包含三个步骤的向导 . 我有一个数组中的步骤别名列表:

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

    然后,我使用以下代码来确定当前别名:

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

    免责声明:我没有试过看看它是否适用于路由参数 .

相关问题