Angular 2でルートデータをアプリコンポーネントに取り込む方法 質問する

Angular 2でルートデータをアプリコンポーネントに取り込む方法 質問する

以下のように、アプリのルーティング モジュールでいくつかのルート データを定義しました。

    const appRoutes:Routes = [
  {path: '', component: LoginComponent, data:[{PageName:"Login Page"}]}]

以下のように、app.component.ts の appRoutes を使用して URL リダイレクト関連の情報を取得できるように、データをグローバルに取得したいと考えています。

export class AppComponent {
  title = 'Welcome';
  constructor(public router: Router, public authenticationService: AuthenticationService) {
    this.router.events.subscribe(event => {
        console.log("Url",event.urlAfterRedirects);
        console.log("Page Name", router[PageName]); //Not working
      }

ActivatedRoute を挿入しようとしましたが、リダイレクトごとに更新されません。

とにかく、ページ名を設定してグローバルに取得できる場所はありますかapp.component.ts

ベストアンサー1

filter代わりにイベントをループしてみてくださいsubscribe

constructor(router:Router, route:ActivatedRoute) {
    router.events
      .filter(e => e instanceof NavigationEnd)
      .forEach(e => {
        this.title = route.root.firstChild.snapshot.data['PageName'];
    });
}

次の動作デモを確認してください:https://plnkr.co/edit/rBToHRaukDlrSKcLGavh?p=info

おすすめ記事