1.app.module.ts

  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { NgModule } from '@angular/core';
  3. import { AppRoutingModule } from './app-routing.module';
  4. import { AppComponent } from './app.component';
  5. import { FooComponent } from './foo/foo.component';
  6. import { LoginComponent } from './home/login/login.component';
  7. //引入路由模块
  8. import { RouterModule, Routes } from '@angular/router';
  9. //声明路由
  10. const appRoutes: Routes = [
  11. { path: 'foo', component: FooComponent },
  12. //路由路径、组件和路由数据
  13. { path: 'login/:id', component: LoginComponent ,data: { title: 'login信息' }},
  14. ];
  15. @NgModule({
  16. //声明模块资源:组件、指令、服务
  17. declarations: [
  18. AppComponent,
  19. FooComponent,
  20. LoginComponent
  21. ],
  22. //依赖模块
  23. imports: [
  24. RouterModule.forRoot(
  25. appRoutes
  26. ),
  27. BrowserModule,
  28. AppRoutingModule
  29. ],
  30. providers: [],
  31. //指定启动组件
  32. bootstrap: [AppComponent]
  33. })
  34. export class AppModule { }


2.app.component.html

  1. <!--routerLinkActive:指定路由被激活的样式
  2. queryParams:路由传参
  3. -->
  4. <a routerLink="/foo" routerLinkActive="active">来到foo</a>
  5. <a routerLink="/login/5" [queryParams]="{name: 'zhangsan'}" routerLinkActive="active">来到login</a>
  6. <!--这边的router-outlet就类似于vue中的router-view-->
  7. <router-outlet></router-outlet>
  8. #3.login.component.ts
  9. import { Component, OnInit } from '@angular/core';
  10. import { ActivatedRoute } from '@angular/router';
  11. import { Location } from '@angular/common';
  12. @Component({
  13. selector: 'app-login',
  14. templateUrl: './login.component.html',
  15. styleUrls: ['./login.component.less']
  16. })
  17. export class LoginComponent implements OnInit {
  18. //声明id
  19. public id:string;
  20. //将route和location注入到构造函数
  21. constructor(
  22. private route: ActivatedRoute,
  23. private location: Location
  24. ) { }
  25. ngOnInit() {
  26. //获取路由中的 参数信息
  27. this.id = this.route.snapshot.paramMap.get('id')
  28. //获取路由中的data 信息
  29. //console.log(this.route.snapshot.data.title)
  30. //获取路由参数的信息
  31. console.log(this.route.snapshot.queryParams)
  32. //获取当前路径,回退
  33. //console.log(this.location.path())
  34. //this.location.back();
  35. }
  36. }

3.login.components.html

  1. <p>login works! {{id}}</p>