[Angular 2 Router] Configure Your First Angular 2 Route
Using the Angular 2 router requires defining routes, passing them in to the RouterModule.forRoot
and then importing the configured RouterModule
into your main App Module.
Use the Wiki Search as example project.
Create a HomeComponent to contain every other components. Then in out app.component.html, we can just use router outlet to render the application:
app.component.ts:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: '<router-outlet></router-outlet>', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; }
app.routes.ts:
import {HomeComponent} from "./home/home.component"; import {RouterModule} from "@angular/router"; const routes = [ {path: '', component: HomeComponent} ]; export default RouterModule.forRoot(routes);
The defualt component is HomeComponent. Export this config to the app.module.ts:
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import {HttpModule, JsonpModule} from '@angular/http'; import { AppComponent } from './app.component'; import { SearchBarComponent } from './home/search-bar/search-bar.component'; import { ResultListComponent } from './home/result-list/result-list.component'; import {SharedServiceModule} from "./home/shared/index"; import {CommonModule} from "@angular/common"; import {API_URL} from "./home/shared/constance.service"; import { MdButtonModule } from '@angular2-material/button'; import {MdInputModule} from "@angular2-material/input"; import {MdListModule} from "@angular2-material/list"; import {MdToolbarModule} from "@angular2-material/toolbar"; import { HomeComponent } from './home/home.component'; import appRoutes from './app.routes'; @NgModule({ declarations: [ AppComponent, SearchBarComponent, ResultListComponent, HomeComponent ], imports: [ MdButtonModule.forRoot(), MdInputModule.forRoot(), MdToolbarModule.forRoot(), MdListModule.forRoot(), appRoutes, BrowserModule, FormsModule, CommonModule, HttpModule, JsonpModule, SharedServiceModule.forRoot() ], providers: [ { provide: API_URL, useValue: `https://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK` } ], bootstrap: [AppComponent] }) export class AppModule { }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具