Angular2 路由入门学习

百般思念 提交于 2019-12-16 20:27:35

模块是基础,接下来看一下路由,路由就是整个项目的一根线,串联着各个项目的各个模块。

还是用例子来记录,看图说话。

NewImage

先准备几个组件

创建项目

ng new routestest

创建组件

ng g c one-component

ng g c two-component

ng g c page-not-found-component

创建对应的module的routes模块

ng g m app-routes

NewImage

app-routes.module.ts文件

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';

import { OneComponentComponent } from './one-component/one-component.component';
import { TwoComponentComponent } from './two-component/two-component.component';
import { PageNotFoundComponentComponent } from './page-not-found-component/page-not-found-component.component';

export const appRoutes = [
    {
        path: '',
        redirectTo: 'one',
        pathMatch: 'full'
    },
    {
        path: 'one',
        component: OneComponentComponent
    },
    {
        path: 'two',
        component: TwoComponentComponent
    },
    {
        path: '**', //fallback router must in the last
        component: PageNotFoundComponentComponent
    }
];
@NgModule({
    declarations: [
        OneComponentComponent,
        TwoComponentComponent,
        PageNotFoundComponentComponent
    ],
  imports: [
        RouterModule.forRoot(appRoutes)
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutesModule { }

app.module.ts文件

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutesModule } from './app-routes.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    AppRoutesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html文件

<h1>

  {{title}}

</h1>

<nav>

  <a routerLink='one'>one</a>

  <a routerLink='two'>two</a>

  <a routerLink='three'>three</a>

</nav>

<router-outlet></router-outlet>

这里就完成了路由的配置

NewImage

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!