1.app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FooComponent } from './foo/foo.component';
import { LoginComponent } from './home/login/login.component';
//引入路由模块
import { RouterModule, Routes } from '@angular/router';
//声明路由
const appRoutes: Routes = [
{ path: 'foo', component: FooComponent },
//路由路径、组件和路由数据
{ path: 'login/:id', component: LoginComponent ,data: { title: 'login信息' }},
];
@NgModule({
//声明模块资源:组件、指令、服务
declarations: [
AppComponent,
FooComponent,
LoginComponent
],
//依赖模块
imports: [
RouterModule.forRoot(
appRoutes
),
BrowserModule,
AppRoutingModule
],
providers: [],
//指定启动组件
bootstrap: [AppComponent]
})
export class AppModule { }
2.app.component.html
<!--routerLinkActive:指定路由被激活的样式
queryParams:路由传参
-->
<a routerLink="/foo" routerLinkActive="active">来到foo</a>
<a routerLink="/login/5" [queryParams]="{name: 'zhangsan'}" routerLinkActive="active">来到login</a>
<!--这边的router-outlet就类似于vue中的router-view-->
<router-outlet></router-outlet>
#3.login.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {
//声明id
public id:string;
//将route和location注入到构造函数
constructor(
private route: ActivatedRoute,
private location: Location
) { }
ngOnInit() {
//获取路由中的 参数信息
this.id = this.route.snapshot.paramMap.get('id')
//获取路由中的data 信息
//console.log(this.route.snapshot.data.title)
//获取路由参数的信息
console.log(this.route.snapshot.queryParams)
//获取当前路径,回退
//console.log(this.location.path())
//this.location.back();
}
}
3.login.components.html
<p>login works! {{id}}</p>