1.新建router.ts,路由配置页面
// 需要从路由模块中引入Routes类
import { Routes } from '@angular/router';
// 对于需要用url链接的组件,需要从文件中导入
import { AllPeopleComponent } from './all-people/all-people.component';
import { HomePageComponent } from './home-page/home-page.component';
// export 导出供其他模块导入 这是一个数组,数组中没一个元素是一个对象,最常见的是这个对象有2个属性,分别是path(对应url)和component(对应组件),直观上url中输入一个路径,在数组中查找path,如果有对应的话就在指定区域显示与path对应的组件。
export const rootRouterConfig: Routes = [
{
path: '', // http://localhost:4200
component: HomePageComponent
},
{
path: 'all-people', // http://localhost:4200/all-people
component: AllPeopleComponent
},
]
2.在app.module.ts 根模块中配置路由
// 在根模块中导入路由配置
import { rootRouterConfig } from './app.routes'; // 注意没有.ts
// 需要调用RouterModule.forRoot()方法
import { RouterModule } from '@angular/router';
// 创建路由模块
const rootRouterModule: ModuleWithProviders = RouterModule.forRoot(rootRouterConfig);
// 根路由模块默认提供的路由策略为PathLocationStrategy(另外一个是HashLocationStrategy)。
// PathLocationStrategy路由策略需要一个base路径,设置base路径有2种方式,最简单的是在index.html中设置<base>
// 路由策略:pathLocationStrategy // const rootRouterModule: ModuleWithProviders = RouterModule.forRoot(rootRouterConfig);
// 路由策略:HashLocationStrategy // const rootRouterModule: ModuleWithProviders = RouterModule.forRoot(rootRouterConfig, {useHash: true}); @NgModule({ declarations: [],
// 导入路由模块 imports: [rootRouterModule], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
配置有两种:1.imports中配置,如上
2.providers中配置:
@NgModule({
imports:[RouterModule.forRoot(routes)],
providers:[ {provide: LocationStrategy, useClass: HashLocationStrategy} ]
})
3.在app.component中引入 (html页面中)
————————————————————————————————————————————————————————
注意:PathLocationStrategy 与HashLocationStragegy 区别
PathLocationStrategy
angular2的默认策略,也就是HTML5路由,使用这个路由的常规路径就是/concat,/about,不带#,这种策略需要后台配置支持,因为我们的应用是单页面应用,如果后台没有正确的配置,当用户在浏览器从http:/10.0.0.1/concat跳转到http:/10.0.0.1/about或者刷新时就会返回404,需要在服务端里面覆盖所有的路由情况(后端可以通过nginx或者apache等配置)。
HashLocationStragegy
适用于基于锚点标记的路径,比如/#/concat,/#/about,后端只需要配置一个根路由即可。
订制自己的路由策略
通过扩展LocationStragegy类并实现一些方法,定制自己的策略。
总结
hash方案:路径比较丑,但是兼容老的浏览器,如果应用需要兼容低版本浏览器推荐使用
纯h5方案:只支持高版本浏览器
ng2目前只支持高版本浏览器,所以开发只要用了ng2,就无法兼容低版本浏览器 O(∩_∩)O~~