Angular 2 Injecting ActivatedRoute returns root ro

2019-07-25 15:49发布

问题:

I have the following routes that I import to app module:

// app.routing.ts
const routes: Routes = [
  {
    path: '',
    component: MainLayoutComponent,
    children: [
      {
        path: '', redirectTo: 'home', pathMatch: 'full'
      },
      {
        path: 'home', loadChildren: 'app/home/home.module#HomeModule'
      }
    ] 
  }
]

export const routing: ModuleWithProviders = RouterModule.forRoot(routes);

// app.module.ts
import {BrowserModule} from '@angular/platform-browser';
import {AppComponent} from './app.component';
import {CoreModule} from './core/core.module';
import {routing} from './app.routing';
import {NgModule} from '@angular/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    CoreModule,
    routing
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Then, in the Home module I have:

// home.routing.ts
const routes: Routes = [
  {
    path: '',
    component: HomeComponent,
    data: {
      pageTitle: 'Home'
    }
  }
];
export const homeRoutes: ModuleWithProviders = RouterModule.forChild(routes);

// home.module.ts
import {NgModule} from '@angular/core';
import {CommonModule} from '@angular/common';
import {HomeComponent} from './home.component';
import {homeRoutes} from './home.routing';

@NgModule({
  imports: [
    CommonModule,
    homeRoutes
  ],
  declarations: [HomeComponent]
})
export class HomeModule {
}

I want to get data for the route, I have component HeaderComponent which is located in the Layout module. This module doesn't contains any routes, just layout components. and I want to get data there:

export class HeaderComponent implements OnInit {
   constructor(private activatedRoute: ActivatedRoute,
            private router: Router) {
   }

   ngOnInit() {
      this.activatedRoute.data
        .subscribe(d => {
         console.log(d);           
      });       
   }
}

But, object is empty all the time. I noticed that activatedRoute is different, it's for MainLayoutComponent:

In order to get exactly my route for the /home I have to go to the children twice and there will be activatedRoute that I need and there is my pageTitle in the data.

The question is, how to get the correct activatedRoute? I dont want to have loop that go to the children until they will finished.
PS. This is template for MainLayoutComponent:

<app-header></app-header>
<div class="container">
  <div class="wrapper">
    <router-outlet></router-outlet>
  </div>
</div>