简体   繁体   中英

Angular routing, must child module be imported before Parent?

I am currently upgrading my angular knowledge from version 1.x to 2+ and I am having some trouble understanding parts of the RouterModule.

I have a root routing module defined and imported into my root module. Then I have two child modules, each with their own routing module that are added using forChild instead of forRoot. These child routing modules are added into their respective modules which in turn are added to the root module. This, as I understand, is still correct (and it works).

What is confusing me is that it seems there are some requirements to the order in which the root routing module and the Child modules are imported.

See snippet below of the imports in the root module.

imports: [
    BrowserModule,
    SharedMaterialModule,
    BrowserAnimationsModule,
    Child1Module
    Child2Module,
    AppRoutingModule
  ],

That works. However if I switch to this:

imports: [
    BrowserModule,
    SharedMaterialModule,
    BrowserAnimationsModule,
    Child2Module,
    AppRoutingModule
    Child1Module
  ],

I can no longer use routerLink from Child2Module to Child1Module. It always redirects to the default paths defined in root routing module.

I have searched a bit and I cannot really find a clearcut answer to what is causing this behaviour (though I'm suspecting it might have to do with lazy loaded modules?!).

Help is greatly appreciated.

Angular uses strategy called 'first match wins' when tring to choose right route based on path. In your app root routing you define wildcard route. If you place AppRoutingModule before Child1Module and try to redirect from Child2Module to Child1Module then first matched route will be wildcard from AppRoutingModule. Here you have more details about it: https://angular.io/guide/router#define-a-wildcard-route

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM