angular4路由基础运用

来源:互联网 发布:单片机原理及 编辑:程序博客网 时间:2024/06/11 14:50

1.base href> 元素

大多数带路由的应用都要在index.html<head>标签下先添加一个<base>元素,来告诉路由器该如何合成导航用的URL。

如果app文件夹是该应用的根目录(就像我们的范例应用一样),那就把href的值设置为下面这样:

src/index.html (base-href)
<base href="/">


2.从路由库中导入

Angular的路由器是一个可选的服务,它用来呈现指定的URL所对应的视图。 它并不是Angular核心库的一部分,而是在它自己的@angular/router包中。 像其它Angular包一样,我们可以从它导入所需的一切。

import { RouterModule, Routes } from '@angular/router';

3.

每个带路由的Angular应用都有一个Router(路由器)服务的单例对象。 当浏览器的URL变化时,路由器会查找对应的Route(路由),并据此决定该显示哪个组件。

路由器需要先配置才会有路由信息。 下面的例子创建了四个路由定义,并用RouterModule.forRoot方法来配置路由器, 并把它的返回值添加到AppModuleimports数组中。



const appRoutes: Routes = [
  { path: 'crisis-center', component: CrisisListComponent },//path后面不能有/斜杠
  { path: 'hero/:id',      component: HeroDetailComponent },

  {
    path: 'heroes',
    component: HeroListComponent,
    data: { title: 'Heroes List' }
  },
  { path: '',
    redirectTo: '/heroes',
    pathMatch: 'full'
  },
  { path: '**', component: PageNotFoundComponent }
];


@NgModule({
  imports: [
    RouterModule.forRoot(
      appRoutes,
      { enableTracing: true } // <-- debugging purposes only
    )
    // other imports here
  ],
  ...
})
export class AppModule { }

4.

这里的路由树组appRoutes描述如何进行导航。 把它传给RouterModule.forRoot方法并传给本模块的imports数组就可以配置路由器。

每个Route都会把一个URL的path映射到一个组件。 注意,path不能以斜杠(/开头。 路由器会为解析和构建最终的URL,这样当我们在应用的多个视图之间导航时,可以任意使用相对路径和绝对路径。

路由出口

有了这份配置,当本应用在浏览器中的URL变为/heroes时,路由器就会匹配到pathheroesRoute,并在宿主视图中的RouterOutlet之后显示HeroListComponent组件。

<router-outlet></router-outlet><!-- Routed views go here -->

5.路由器链接

template: `
  <h1>Angular Router</h1>
  <nav>
    <a routerLink="/crisis-center" routerLinkActive="active">Crisis Center</a>
    <a routerLink="/heroes" routerLinkActive="active">Heroes</a>
  </nav>
  <router-outlet></router-outlet>
`

6.其他用法

一、

import { Component } from '@angular/core';


@Component({
  template: `
    <h2>HEROES</h2>
    <p>Get your heroes here</p>


    <button routerLink="/sidekicks">Go to sidekicks</button>
  `
})
export class HeroListComponent { }

二、

constructor(
  private router: Router,
  private service: HeroService
) {}


template: `
  <h2>HEROES</h2>
  <ul class="items">
    <li *ngFor="let hero of heroes | async"
      (click)="onSelect(hero)">
      <span class="badge">{{ hero.id }}</span> {{ hero.name }}
    </li>
  </ul>


  <button routerLink="/sidekicks">Go to sidekicks</button>
`


onSelect(hero: Hero) {
  this.router.navigate(['/hero', hero.id]);
}






















原创粉丝点击