Mark Sandman Mark Sandman - 4 months ago 37
TypeScript Question

TypeScript importing / DI a const value between Angular2 Classes / Components

Hi there in my Angular2 app I have a routes file called

routes.ts
like so (I have only included a few routes here)...

export const routes:DisplayRoutes = [
{
path: '',
display: 'Home',
component: HomeComponent
}, {
path: 'teams',
display: 'Teams',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
}
]
}, {
path: 'contact',
display: 'Contact',
component: LeftSubNavigation,
index: {
component: DetailMoreLayout
},
children: [
{
path: ':id',
component: DetailMoreLayout
}
]
}
];


DisplayRoutes
is a custom type I made by extending the Route object, now I have another component folder with a component file in it, this is called
navigation.component.ts
. In this file I want to import the routes I declared in the
routes.ts
I've tried numerous ways (using
@Inject(routes)
but I just keep getting errors in the console...

import {
routes
} from '../routes';

@Component({
selector: 'navigation',
templateUrl: './navigation.component.html',
directives: [],
pipes: []
})
export class NavigationComponent {
menuOpen:boolean = false;
routes:any;

constructor(private routes: routes, private router:Router) {

this.routes = routes; // this won't work, how do I get hold of a copy of my routes... I need to loop through them, etc, etc...

// more code below... etc...
}


With the above I get the error
Can't resolve all parameters for NavigationComponent: (?, Router)'


When I change the constructor to:

constructor(@Inject(routes) routes:DisplayRoutes, private router:Router)


I get the error:
browser_adapter.ts:82 ORIGINAL EXCEPTION: No provider for [object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]!


Any help would be appreciated. I am sure it is really easy, I just don't seem to be able to make this work!

Answer

No need to inject into the constructor. The import statement is enough to have access to the constant:

import {routes} from '../routes';

@Component({
    selector: 'navigation',
    templateUrl: './navigation.component.html'
})
export class NavigationComponent {

    menuOpen: boolean = false;
    routes: any;

    constructor(private router:Router) {
        this.routes = routes; 
    }
}

If for some reason you do not want to assign it in the constructor which does seem a bit odd. You can also use a getter property:

import {routes} from '../routes';

@Component({
    selector: 'navigation',
    templateUrl: './navigation.component.html'
})
export class NavigationComponent {

    menuOpen: boolean = false;

    get routes(): any {
       return routes;
    }

    constructor(private router:Router) {}
}

Whatever floats your boat :)