angular6路由配置

文章参考

路由与导航

(下载官方案例,对比齐代码)[https://angular.cn/generated/zips/router/router.zip]

配置路由模块

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

import { NewsComponent }   from '../page/news/news.component';
import { HeaderComponent }   from '../page/header/header.component';
import { HttpdemoComponent }   from '../page/httpdemo/httpdemo.component';

const routes: Routes = [
  { path: '', redirectTo: '/news', pathMatch: 'full' },
  { path: 'news', component: NewsComponent },
  { path: 'header', component: HeaderComponent },
  { path: 'httpdemo', component: HttpdemoComponent },
];

@NgModule({
// 是根路由配置,必须使用forRoot(routes)这个API
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

在NgModule中引入路由模块

/**
 * 告诉angular 如何组装应用
 */

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule }   from '@angular/forms';
import { HttpClientModule }   from '@angular/common/http';

import { AppComponent } from './app.component';
import { HeaderComponent } from './page/header/header.component';
import { NewsComponent } from './page/news/news.component';
import {StorageService} from './page/service/storage.service'
import { AppRoutingModule }     from './router/app-routing.module';
import { HttpdemoComponent } from './page/httpdemo/httpdemo.component';

//@NgModule 装饰器将AppModule标记为Angular 模块类(也叫做 NgModule类)
// @NgModule 接收一个元数据对象,告诉Angular 如何编译和启动应用
@NgModule({
  // 引入当前项目运行的组件,自定义组件都需要引入并且在这里声明
  // 依赖注入
  declarations: [
    AppComponent,
    HeaderComponent,
    NewsComponent,
    HttpdemoComponent
  ],
  // 当前项目依赖哪些模块
  imports: [
    BrowserModule,
    HttpClientModule,
    // 如果要引入双向绑定,则需要引入FormModule
    FormsModule,
    // 引入路由配置模块
    AppRoutingModule
  ],
  // 定义服务
  providers: [
    StorageService
  ],
  // 默认启动哪个组件
  bootstrap: [AppComponent]
})

// 根模块不需要导出任何东西,因为其他组件不需要导入根模块,但是一定要写
export class AppModule { }

应用路由模块的时候,对应的组件也需要在declarations 中声明,否则会出现编译没有问题,但是在浏览器中不显示的奇怪现象。

猜你喜欢

转载自blog.csdn.net/hbiao68/article/details/84562972