要想使用路由我们先要在app.module中导入router服务
import{RouterModule}from'@angular/router';
使用这段导入module
@NgModule({
imports:[
RouterModule.forRoot([
//path对应的是点击链接显示的内容,component内容是调用的conponent类的名字
//HeroComponentComponent是使用import导入的自己创建的component
{path:'test',component:HeroComponentComponent}
])
],
exports:[RouterModule]
})
在html中使用的例子<a routeLink="/test"></a>
就自动访问上面的这个RouterModuler
提取路由
上面的最基础的使用路由,下面我们将路由提取出来,
我们先创建一个自己的路由文件test.routing.module.ts文件,在文件中我们同样要导入NoModule 和RouterModule
import { NgModule} from '@angular/core'
import {RouterModule} from '@angular/router'
import {LoginComponent}from './login.component'
@NgModule({
imports:[
//加入自己想要创建的路由
RouterModule.forRoot([{path:'test',component:LoginComponent}])
],
exports:[RouterModule]
})
export class TestRoutingModule{
}
这样这个路由的文件就创建完成了,但是现在还没有生效,我们想要让路由生效那么我们需要在app.module中注入我们创建的module
首先导入component
import {TestRoutingMocdule} from './test.routing.module';
然后再app.module中的imports中注入我们创建的路由module
imports: [
AppRoutingMocdule
]
现在提取路由的步骤就完成了
下面那我们尝试使用路由来传递参数
有了上面的基础我们直接说声明路由的部分
在声明路由的时候在path中使用path:’路径:id’的方式说明这个是带有参数的链接
RouterModule.forRoot([
{path:'test:id',component:HeroComponentComponent}
])
然后a标签中的路径使用的是<a routeLink="/test/参数"></a>
那么还需要
//导入两个包
import { ActivatedRoute, Params } from '@angular/router';
构造器中注入服务
constructor( private route: ActivatedRoute}
//接受参数的方法,route和构造器中的route同名 key是带参数路由中声明的变量名比如这里是id
this.route.params.forEach((params: Params) => {
let id = params['key'];
this.heroService.getHero(id)
.then(hero => this.hero = hero);
});
使用事件跳转路由
使用路由的时候会用到不使用链接的方式跳转路由,那么就用到了使用事件跳转路由
首先在component的构造器中注入Router,当然是要导入Router服务的
constructor(public route:Router){
}
//使用事件跳转页面,第二个参数是传递的参数
this.router.navigate(['ModifyModel', {model: this.modelInfo}]);
//路由后退页面
goBack(): void {
this.location.back();
}
//redirectTo重定向
{ path: ‘’, pathMatch: ‘full’, redirectTo: ‘/inbox’ }
到这里路由的简单使用就够了