6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Angular] ActivatedRouteまとめ

Last updated at Posted at 2020-05-13

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'));
    });
  • 結果
スクリーンショット 2020-05-13 22.31.25.png

queryParams

クエリパラメータの取得

  • URL
    • http://localhost:4200/test?param1=foo&param2=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'));
     });
  • 結果
スクリーンショット 2020-05-13 22.35.09.png

fragment

※フラグメント、「#〜」以降の文字列

  • URL
    • http://localhost:4200/test#param1=foo&param2=hoge
  • 実装
app.routing.ts
const routes: Routes = [
  {path: 'test', component: TestComponent},
];
test.component.ts
    this.route.fragment.subscribe( fragment => {
      console.log(fragment);
    });
  • 結果
スクリーンショット 2020-05-13 22.45.07.png

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(' '));
    });
  • 結果
スクリーンショット 2020-05-13 22.25.42.png

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);
    });
  • 結果
スクリーンショット 2020-05-13 22.26.40.png

以上です

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?