技術

[Angular] router-outletの外で現在のurlを取得

投稿日:

こんにちは、コーテッグのこやまです。
Angularでapp.componentや、そのほか必要なときに、route-outletの外から現在のurlを取得したい場合のコードです。

import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';

~~

constructor(
  private router: Router
) {}

ngOnInit() {
  this.router.events
    .pipe(filter(e => e instanceof NavigationEnd))
    .subscribe((e: NavigationEnd) => {
        console.log(e.url) // 現在のパスを出力
      });
  }

最初は何も考えずにActivatedRouteを使おうとしていましたが、
ドキュメントに以下のようにあるので、使いません。
“Contains the information about a route associated with a component loaded in an outlet.”
https://angular.jp/api/router/ActivatedRoute

router.eventsは16個あったので、filterしないといっぱい出力されてしまします。
1つでいいので、”An event triggered when navigation ends successfully.”のNavigationEndにします。
https://angular.io/guide/router

これで取れます。
私はヘッダーを共通で使って、特定のurlのときに表示を変更するというのに使いました。

-技術
-

執筆者:


comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

関連記事

go

【Golang】package strconvのintSize = 32 << (∧uint(0) >> 63)は何をしているのか

こんにちは Goのstrconvのパッケージを読んでたらintSizeというもの …

[Xcode] SDK Version Issue – This app was built with the iOS 12.0 SDK. Starting March 2019, all iOS apps submitted to the App Store must be built with the iOS 12.1 SDK or later, included in Xcode 10.1 or later.

こんにちは。たなかです。 2019年、ブログ初更新になります。今年もよろしくお願 …

ブラウザでRailsのrouting設定を確認する

こんにちは Railsでroutingを確認する時、コマンドでrails rou …

CentOS7でDocker内部からpingができない(外部通信できない)!

どうもなかたです CentOS7にDocker入れて、Docker内部から外に向 …

git_logo

[Git] どのコミットでバグが入ったか原因究明する方法【git blame】

こんにちは。さとうです。 今回はgitを使って、どのコミットでバグが入ったか原因 …