TypeScript导入/ DI Angular2类/组件

时间:2016-08-02 12:08:56

标签: typescript angular dependency-injection

您好,在我的Angular2应用程序中,我有一个名为routes.ts的路径文件,就像这样(我这里只包含了几条路线)......

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是我通过扩展Route对象而创建的自定义类型,现在我有另一个组件文件夹,其中包含一个组件文件,这称为navigation.component.ts。在这个文件中,我想导入我在routes.ts中声明的路由我已尝试过多种方式(使用@Inject(routes)但我只是在控制台中出现错误...

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...
    }

有了上述内容,我收到错误Can't resolve all parameters for NavigationComponent: (?, Router)'

当我将构造函数更改为:

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

我收到错误: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]!

任何帮助将不胜感激。我相信这很容易,我似乎无法做到这一点!

1 个答案:

答案 0 :(得分:1)

无需注入构造函数。 import语句足以访问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; 
    }
}

如果由于某种原因你不想在constructor中分配它看起来有点奇怪。您还可以使用getter属性:

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) {}
}

无论你的船漂浮着什么:)