【问题标题】:Angular 7 router navigate can not route to child compoentAngular 7路由器导航无法路由到子组件
【发布时间】:2019-07-27 00:17:19
【问题描述】:

我使用 Angular 7 做一个 Web 应用程序项目。我遇到了一个问题,路由器导航无法使用 this.router.navigate([/home/fetch-data]) 路由到子组件。

import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { CounterComponent } from './counter/counter.component';
import { HomeComponent } from './components/home/home.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
  {
    path: 'home',
    component: HomeComponent,
    data: { bc: "NAVI.HOME" },
    children: [
      {
        path: 'fetch-data',
        component: FetchDataComponent,
        data: { bc: "VEHICLE.DETAILS" }
      }
    ]
  },
  {
    path: 'counter',
    component: CounterComponent,
    data: { bc: "Counter" }
  },
  // {
  // path: 'home/fetch-data',
  // component: FetchDataComponent,
  // data: { bc: "Home > Counter" }
  // },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  }
];
@NgModule({
  declarations: [],
  imports: [
    RouterModule.forRoot(routes),
    CommonModule,
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }

搜索组件会触发一个函数:

public naviTo(): void {
    this.vehicleService.getVehicleByVin(this.vehicle.vin);
    this.router.navigate(['../../home/fetch-data']);
    this.messageService.sendMessage("VehicleData");
  }

和 app.component.html

<mat-sidenav-container class="mat-sidenav-container" autosize>
  <mat-sidenav mode="side" class="mat-sidenav" opened>
    <app-side-nav></app-side-nav>
  </mat-sidenav>
  <mat-sidenav-content>
    <div class="app-header">
      <app-header></app-header>
    </div>
    <div class="mat-sidenav-content">
      <main class="content">
        <app-breadcrumb></app-breadcrumb>
        <router-outlet></router-outlet>
      </main>
    </div>
  </mat-sidenav-content>
</mat-sidenav-container>

这些都是相关的代码。 函数 naviTo() 在 search.component 中,这个搜索组件是标题组件的子组件。 home.component 由侧导航导航。

形成rotuers的定义,大家可以理解fetch-data组件是home的子组件,但在实现上并不是真正的父子关系。

问题是它不会通过函数 naviTo() 路由到子组件。我尝试了很多可能性,但没有奏效。 也许我已经通过了一些东西。

任何解决方案?

最好的问候,

狮子座

【问题讨论】:

  • 试试:this.router.navigate(['/home/fetch-data']);

标签: angular routing navigation router


【解决方案1】:

这里你只需要./ 相对于家庭组件(父)。

解决方案:

 public naviTo(): void {
    this.vehicleService.getVehicleByVin(this.vehicle.vin);
    this.router.navigate(['./fetch-data']);
    this.messageService.sendMessage("VehicleData");
  }

希望对您有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2019-12-19
    相关资源
    最近更新 更多