本篇介紹如何使用Router Parameters來傳入路由參數,並在Component中取得參數。
首先使用Angular CLI建立一個Angular專案。
專案建好後先把app.component.html的預設內容刪除,修改如下
app.component.html
<h1>Angular Router Paramter Demo</h1>
<router-outlet></router-outlet>
接著建立一個HelloComponent元件。
HelloComponent建好後,開啟app-routing.module.ts。
在const routes: Routes陣列中新增導向HelloComponent的Route:{ path:'hello/:name', component:HelloComponent }。
hello/後面的:name標記就是Router Parameter,在URL hello/<name>後的路徑本身除了是path外,也是一個參數,key值為name,所以叫做路由參數Router Parameter。
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HelloComponent } from './hello/hello.component';
const routes: Routes = [
{ path:'hello/:name', component:HelloComponent } // <-- 新增導向HelloComponent的路徑 :name為RouterParameter
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
修改hello.component.html如下。
hello.component.html
<h1>Hello {{ name }}</h1>
{{ name }}用來顯示HelloComponent.name屬性的值。
接著修改hello.component.ts,在HelloComponent的建構式中注入ActivatedRoute物件,並在Component初始方法ngOnInit()中從ActivatedRoute物件route中取得Router Parameter,並賦值給HelloComponent.name。
hello.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-hello',
templateUrl: './hello.component.html',
styleUrls: ['./hello.component.css']
})
export class HelloComponent implements OnInit {
constructor( private route: ActivatedRoute ) { } // <-- 在建構式注入ActivatedRoute
name = ''; // <-- 新增屬性
ngOnInit() {
this.name = this.route.snapshot.paramMap.get('name'); // <-- 從route的snapshot取得Router Parameter:name
}
}
Route路徑及參數資訊存放在注入的ActivatedRoute物件,其屬性snapshot為ActivatedRouteSnapshot,記錄了在路由當時的Router Parameter的值。
設定好後執行ng serve啟動Angular專案。
在瀏覽器位址輸入http://localhost:4200/,畫面如下。
接著在後面加上/hello/ケンシロウ,
也就是http://localhost:4200/hello/ケンシロウ,輸入後效果如下。
/hello後面的路由參數為必填,如果只是輸入http://localhost:4200/hello並無法找到對應的URL,在console會顯是下面錯誤。
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'hello'
Error: Cannot match any routes. URL Segment: 'hello'
參考:
沒有留言:
張貼留言