2017-08-29 62 views
1

定义路由在角度4文档上路由的代码段被给出为如下:在角4

导入模块:

import { RouterModule, Routes } from '@angular/router'; 

路由的实施例:

const appRoutes: Routes = [ 
    { path: 'crisis-center', component: CrisisListComponent }, 
    { path: 'hero/:id',  component: HeroDetailComponent }, 
    { 
    path: 'heroes', 
    component: HeroListComponent, 
    data: { title: 'Heroes List' } 
    }, 
    { path: '', 
    redirectTo: '/heroes', 
    pathMatch: 'full' 
    }, 
    { path: '**', component: PageNotFoundComponent } 
]; 

@NgModule({ 
    imports: [ 
    RouterModule.forRoot(
     appRoutes, 
     { enableTracing: true } // <-- debugging purposes only 
    ) 
    // other imports here 
    ], 
    ... 
}) 
export class AppModule { } 

我问题是为什么我们必须将路线定义为const appRoutes: Routes = [...]而不是const appRoutes = [...],它似乎也是这样工作的。

回答

4

这就是为什么Typescript在那里,为了给予强类型,以便我们知道变量的类型, 没有给出任何/空白,它需要默认为any。这就是它仍然有效的原因。 通过不使用类型,您可以消除Angular中的类型的优势。

+0

我熟悉类型,布尔值,数字,字符串等等的变量。上例中是一个“自定义”类型的路由被创建?这与导入的路线模块有任何关系吗? – DanT29

+0

@ DanT29这个对象数组是一种路由。路由器模块在启动时需要一组路由,所以我们导入数组 –

1

由于TypeScript是一种类型化语言,因此最好定义变量的类型,以便自动完成/编译错误检测能够正常工作。