質問
Angularを使ってSPAの構築にチャレンジしています。ルーティング用のモジュールの定義方法が大まかに把握できて、メンテナンス性の高いディレクトリ構造・モジュール分割方法を模索している段階です。
その過程で、children
を使ってネストする方法や、loadChildren
を使ってLazyLoadingする方法を学びました。
さて、以下のようなルーティングを定義したときの:groupName
と:userId
の取得方法について困っています。
typescript
1import { NgModule } from '@angular/core'; 2import { Routes, RouterModule } from '@angular/router'; 3 4const routes: Routes = [ 5 { path: 'group/:groupName', children: [ 6 { path: 'user', children: [ 7 { path: '', loadChildren: './user-list/user-list.module#UserListPageModule' }, 8 { path: ':userId', loadChildren: './user-detail/user-detail.module#UserDetailPageModule' }]}]}, 9]; 10 11@NgModule({ 12 imports: [RouterModule.forRoot(routes)], 13 exports: [RouterModule] 14}) 15export class AppRoutingModule { }
UserDetailPage
で:groupName
と:userId
を利用しようとすると、以下のように:userId
はthis.route.snapshot.paramMap
から得ることができますが、:groupName
の方はthis.route.parent.parent.parent.snapshot.paramMap
から取得する必要があります。
typescript
1import { Component } from '@angular/core'; 2import { ActivatedRoute } from '@angular/router'; 3 4@Component({ 5 selector: 'app-user-detail', 6 templateUrl: './user-detail.component.html', 7 styleUrls: ['./user-detail.component.scss'] 8}) 9export class UserDetailComponent { 10 11 // ここがわかりづらく、可能であれば改修したい 12 groupName = this.route.parent.parent.parent.snapshot.paramMap.get('groupName'); 13 userId = this.route.snapshot.paramMap.get('userId'); 14 15 constructor( 16 private route: ActivatedRoute, 17 ) { } 18 19}
各ページのコンポーネントがルーティング中での自身の階層の深さを知っている必要があり、実装面で綺麗ではないと思ってしまいました。URL中に含まれるパラメタをシンプルに取得する良い方法を教えていただきたいです。
今までWebアプリケーション開発はRuby on Railsで行なっており、パラメーターはコントローラー中であればどこでもparams[:group_name]
のように取得することができていたので、そのように簡単にアクセスできたら扱いやすいと考えて質問させていただきました。
宜しくお願いいたします。
環境
- Node.js v10.4.1
- @angular/cli 7.3.1
- Angular 7.2.5
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。