【问题标题】:Angular Routing is not navigating to child routeAngular Routing 没有导航到子路由
【发布时间】:2020-01-04 18:42:57
【问题描述】:

我有一个菜单组件,我试图从中导航和加载我的子路由的内容 - AboutComponent,它不起作用。下面是我的代码,请帮忙:

URL 显示正确的路由,控制台没有错误。但是 about 组件没有加载

app.component.html:

<app-header></app-header>
<router-outlet></router-outlet>

menu.component.html:

<div class="row menustyle" *ngIf="isMenuClicked">
 <div class="col24" style="padding: 0 20px">
   <ul class="nav navba-nav">
     <li>
        <a *ngFor="let data of navPathData" routerLinkActive="active" 
          routerLink="data.value"
          (click)="goto(data.value)">{{ data.text }}</a>
     </li>
   </ul>
 </div>
</div>

menu.component.ts:

构造函数:

 constructor(private readonly route: ActivatedRoute,
private readonly router: Router, private dataService: DataServiceService) { }

方法: 公共转到(值:字符串):无效{ //this.router.navigate();

this.router.navigate([value], { relativeTo: this.route });

}

app-routing.modulets:

import { MenuComponent } from './menu/menu.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AboutComponent } from './content/about/about.component';

const routes: Routes = [
 { path: '', redirectTo: '/menu', pathMatch: 'full' },
 {
   path: 'menu', component: MenuComponent, children:
    [
     { path: ':id', component: AboutComponent }
    ]
 }
 ];

@NgModule({
imports: [RouterModule.forRoot(routes)],
 exports: [RouterModule]
})
export class AppRoutingModule { }

【问题讨论】:

  • 不应该有[routerLink] 而不是routerLink 吗?如果是这样,您可以摆脱goto 函数。

标签: angular routing


【解决方案1】:

我的解决方案是

 { path: '', redirectTo: '/menu', pathMatch: 'full' },
 {
   path: 'menu', children:
    [
     { path: '', component: MenuComponent }
     { path: ':id', component: AboutComponent }
    ]
 }
 ];

【讨论】:

    【解决方案2】:

    当您将 routerlink 绑定到一个变量时,您需要用方括号将 routerlink 括起来

    [routerLink]="data.value"
    

    根据您的路线设置,您也可能错误地指定了相对路线,您可以尝试['./'+data.value]['/'+data.value]

    如果这仍然不起作用,您可以通过启用跟踪来获取更多路由器调试信息

    RouterModule.forRoot(
          ...,
          { enableTracing: true }
        )
    

    【讨论】:

    • #chrismclarke 我现在给出了:[routerLink]="data.value",它仍然不起作用。你能否帮助我解释一下在哪里使用:['./'+data.value] 或 ['/'+data.value]
    • 你的意思是这样的:[routerLink]="['/'+data.value]"
    • 是的,完全一样。如果它不起作用,你会说什么错误消息?
    猜你喜欢
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 2019-07-27
    • 2017-05-14
    • 2020-08-26
    相关资源
    最近更新 更多