当前位置 : 主页 > 网络编程 > JavaScript >

angular 的路由

来源:互联网 收集:自由互联 发布时间:2021-06-28
路由的一些简单实用代码 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();
  }


}






hero-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 } ]; 博客列表 最多阅读
app-routing.module.ts
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 { }
上一篇:JavaScript 操作cookie
下一篇:javascript回顾
网友评论