路由的一些简单实用代码 import { Component, OnInit } from '@angular/core';import {HeroService} from "../hero.service";import {Router, ActivatedRoute, ParamMap} from "@angular/router";import {Hero} from "../hero";import {Location}
import { Component, OnInit } from '@angular/core'; import {HeroService} from "../hero.service"; import {Router, ActivatedRoute, ParamMap} from "@angular/router"; import {Hero} from "../hero"; import {Location} from "@angular/common"; import 'rxjs/add/operator/switchMap'; @Component({ selector: 'app-hero-detail', templateUrl: './hero-detail.component.html', styleUrls: ['./hero-detail.component.css'] }) export class HeroDetailComponent implements OnInit { hero:Hero; constructor(private hreoService:HeroService,private route:ActivatedRoute,private location:Location) { } ngOnInit():void{ this.route.paramMap.switchMap((parms:ParamMap)=> this.hreoService.getHero(+parms.get("id")) ).subscribe(hero=>this.hero=hero); } goBack():void{ this.location.back(); } }app-routing.module.tshero-detail works!
{{hero.name}} details!
{{hero.id}} 异步取得数据: import { Injectable } from '@angular/core'; import {Hero} from "./hero"; import {HEROES} from "./mock-heroes"; @Injectable() export class HeroService { constructor() { } getHeroes(): Promise{ return Promise.resolve(HEROES); } getHeroesSlowly(): Promise { return new Promise(resolve => { // Simulate server latency with 2 second delay setTimeout(() => resolve(this.getHeroes()), 2000); }); } getHero(id: number): Promise { return this.getHeroes() .then(heroes => heroes.find(hero => hero.id === id)); } } const routes: Routes = [ {path:'',redirectTo:'/dashboard',pathMatch:'full'}, {path:'dashboard',component:DashboardComponent}, { path: 'detail/:id', component: HeroDetailComponent }, { path: 'heroes',component: HerosComponent } ]; 博客列表 最多阅读
import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; const routes: Routes = []; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }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'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }