技術

[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 を使っています。コメントデータの処理方法の詳細はこちらをご覧ください

関連記事

no image

ActiveRecord::Relationのklassメソッドでmodelを取得できる。

こんにちは。コーテッグのこやまです。 モデルに対してallやwhereメソッドを …

no image

[Rails]Deviceのfacebook認証でinvalid_credentials….

こんばんは Deviceでfacebook認証機能を作っていたらinvalid_ …

no image

railsでA server is already running~とでたときの対処法

こんにちは!コーテッグの小山です。 rails使っていて、rails sをすると …

[Ionic]UnhandledPromiseRejectionWarning: CordovaError: Requirements check failed for JDK 1.8 or greater

こんにちわ。田中です。 参画しているプロジェクトで使っているのもあって、現在Io …

no image

CSSのpositionで要素を真ん中寄せにする(JS不要)

positionを使って要素を真ん中寄せにする時は、transform: tra …