Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 get current route's alias

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)?

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

Is it possible?

like image 702
Pietrzm Avatar asked Dec 27 '15 10:12

Pietrzm


2 Answers

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.

The following will print Foo or Bar depending on your active route.

@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);
    }
}
like image 76
konrad Avatar answered Oct 05 '22 10:10

konrad


Can't see a way of getting it, but one alternative is to use RouteData to pass the alias of the route

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

like image 41
Peter M Avatar answered Oct 05 '22 09:10

Peter M