ActivatedRouteのメモです
Angular: 9.1.6
を利用して検証しています
共通
紹介する各処理はこちらのコンポーネントを共通で利用します
test.component.ts
export class TestComponent implements OnInit {
// ActivatedRouteサービスをDIします
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// 各処理を記載
}
}
paramMap
- URL
http://localhost:4200/test/1
- 実装
app.routing.ts
const routes: Routes = [
{path: 'test/:id', component: TestComponent},
];
test.component.ts
this.route.paramMap.subscribe( params => {
console.log(params);
console.log(params.get('id'));
});
- 結果
queryParams
クエリパラメータの取得
- URL
http://localhost:4200/test?param1=foo¶m2=hoge
- 実装
app.routing.ts
const routes: Routes = [
{path: 'test', component: TestComponent},
];
test.component.ts
this.route.queryParamMap.subscribe( params => {
console.log(params);
console.log(params.get('param1'));
console.log(params.get('param2'));
});
- 結果
fragment
※フラグメント、「#〜」以降の文字列
- URL
http://localhost:4200/test#param1=foo¶m2=hoge
- 実装
app.routing.ts
const routes: Routes = [
{path: 'test', component: TestComponent},
];
test.component.ts
this.route.fragment.subscribe( fragment => {
console.log(fragment);
});
- 結果
url
- URL
http://localhost:4200/test/1
- 実装
app.routing.ts
const routes: Routes = [
{path: 'test/:id', component: TestComponent},
];
test.component.ts
this.route.url.subscribe( url => {
console.log(url);
console.log(url.join(' '));
});
- 結果
data
- URL
http://localhost:4200/test
- 実装
app.routing.ts
const routes: Routes = [
{path: 'test', component: TestComponent, data: {testData: 'test'}},
];
test.component.ts
this.route.data.subscribe( data => {
console.log(data);
});
- 結果
以上です