您好,在我的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]!
任何帮助将不胜感激。我相信这很容易,我似乎无法做到这一点!
答案 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) {}
}
无论你的船漂浮着什么:)