为什么在Angular中带参数的路由不起作用?

huangapple go评论61阅读模式
英文:

Why route is not working in Angular with params?

问题

在Angular中有一个简单的路由配置:

const routes: Routes = [
  {
    path: ':name', component: AppComponent,
    children: [
      { path: '1', component: Child1Component },
      { path: '2', component: Child2Component },
    ]
  },
  { path: '**', redirectTo: '/mur', pathMatch: 'full' }
]

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

AppComponent 包含以下内容:

<router-outlet></router-outlet><a href="#" (click)="goto()">Move</a>

其中 goto() 方法如下:

goto() {
  this.router.navigate(["1"]);
}

第一个问题是,当我使用链接 http://localhost:4200/mahmud 时,"Move" 内容会重复出现两次。

第二个问题是,当我点击链接 http://localhost:4200/mahmud/1 时,我没有跟随到该链接,而是重定向回到 http://localhost:4200/mahmud

英文:

There is a simple routing in Angular:

const routes: Routes = [
  {
    path: ':name', component: AppComponent,
    children: [
      { path: '1', component: Child1Component },
      { path: '2', component: Child2Component },
    ]
  },
  { path: '**', redirectTo: '/mur', pathMatch: 'full' }
]

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

The AppComponent contains:

<router-outlet></router-outlet><a href="#" (click)="goto()">Move</a>

Where goto() is:

goto() {
  this.router.navigate(["1"]);
}

First issue is I got content "Move" twice by link http://localhost:4200/mahmud

The second is when I click to I don't follow http://localhost:4200/mahmud/1 I just redirects back in http://localhost:4200/mahmud

答案1

得分: 0

The router.navigate方法接受一个命令数组。根据您提供的路由配置,要访问http://localhost:4200/mahmud/1,您需要先进入/mahmud,然后再进入/1

使用您的代码,将无法跳转到所需的路由,因为1是:id的子路径,而不是主路径。

goto() {
  this.router.navigate(["1"]);
}

假设mahmud代表一个id,您需要先进入mahmud,然后再进入1

goto() {
  this.router.navigate(["mahmud", "1"]);
}

希望这有所帮助 为什么在Angular中带参数的路由不起作用?

英文:

The router.navigate accepts an array of commands. With the routing that you provided, to follow http://localhost:4200/mahmud/1 you need to go to /mahmud and then /1

With your code, will not go to the desired route since 1 is children of :id and not a main path.

goto() {
  this.router.navigate(["1"]);
}

Assuming mahmud represents an id, you need to go to mahmud then 1.

goto() {
  this.router.navigate(["mahmud", "1"]);
}

Hope this helps 为什么在Angular中带参数的路由不起作用?

huangapple
  • 本文由 发表于 2023年7月18日 03:11:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76707458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定