Angular无法导航到子组件

时间:2019-03-06 15:49:31

标签: angular routing navigation

我在用角度7实现路由时遇到了问题。 代码很简单,但是我找不到问题所在。也许你可以帮我。

代码如下:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <div class="container">
    <a routerLinkActive="active" 
       routerLink="/login">Login</a> |

    <a routerLinkActive="active" 
       routerLink="/home/catalog">Homasdfasdfe</a> | 
      
    <a routerLinkActive="active" 
       routerLink="/home/">Home</a> | 

    <a routerLinkActive="active" 
      routerLink="/catalog">Catalog</a> 
      
    <router-outlet></router-outlet>
  </div>
  `,
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

}

app-routing.module.ts:

import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
import { LoginViewComponent } from './views/login/login.component';
import { HomeViewComponent } from './views/home/home.component';
import { CatalogViewComponent } from './views/catalog/catalog.component';

@NgModule({
  declarations: [ 
    LoginViewComponent, HomeViewComponent, CatalogViewComponent
  ],
  imports: [
    RouterModule.forRoot([
      { path: 'login', component: LoginViewComponent },
      { path: 'home', component: HomeViewComponent, children: [
         { path: 'catalog', component: CatalogViewComponent }
      ] },
      { path: 'catalog', component: CatalogViewComponent },
      { path: '**', redirectTo: 'login' }
    ])
  ],
  exports: [
    RouterModule,
  ],
  providers: [],

})
export class AppRoutingModule {}

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app.routing.module';

@NgModule({
  declarations: [ AppComponent],
  imports: [ 
    AppRoutingModule, 
    BrowserModule, FormsModule, HttpModule 
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

问题是,如果我单击Homasdfasdfe,它将显示家庭而不是目录的内容。

有什么解决方案吗?

最诚挚的问候,

狮子座

2 个答案:

答案 0 :(得分:1)

尝试如下更改回家路线。

RouterModule.forRoot([
   { path: 'login', component: LoginViewComponent },
   { path: 'home', children: [
      { path:'', component: HomeViewComponent },
      { path: 'catalog', component: CatalogViewComponent }
   ]},
   { path: 'catalog', component: CatalogViewComponent },
   { path: '**', redirectTo: 'login' }
])

答案 1 :(得分:0)

我认为您的问题是您在子路径中使用“ CatalogViewComponent”组件,然后在其下方的主要道路中使用。 尝试删除主要的“目录”路由,也许可以解决您的问题。