【问题标题】:Url path construction in AngularAngular 中的 URL 路径构建
【发布时间】:2020-01-24 06:22:38
【问题描述】:

我正在使用 Angular 8 和 Django 3。我不明白我的 url 路径在 Angular 中的构建方式。我有一个restaurantlist 组件和一个restaurantdetail 组件,在我的app-routing-module.ts 中有以下路径:

const routes: Routes = [
  {path:'restaurantlist', component:RestaurantlistComponent},
  {path:'restaurantdetail/:id', component:RestaurantViewComponent}
];

在我的restaurantlist.component.html 文件中:

<h2>List of Restaurants</h2>
<ul *ngFor = "let restaurant of restaurants">
<a [routerLink]="['restaurantdetail', restaurant.id]">{{restaurant.name}}</a>  
</ul>

当我点击我的restaurant.component.html 文件中的一个链接时,它尝试发送给我的链接是localhost:4200\restaurantlist\restaurantdetail\2。我不想要这个,我希望它把我发送到localhost:4200\restaurantdetail\2,因为这就是我设置 django url 的方式。为什么它继承了 url 的 restaurantlist 部分(好像它是这个组件的子视图或其他东西),我该如何摆脱它?这是否与我如何定义指向restaurantlist 组件的链接有关:

<a [routerLink]="'/restaurantlist'">See Available Restaurants</a>

感谢任何输入。

【问题讨论】:

  • 尝试 /restaurantDetail 使用绝对路线

标签: angular url routing


【解决方案1】:

没有/ 的路线是相对路线,这意味着您“深入”到路线中。

localhost/main -> 路由到list -> localhost/main/list -> 路由到detail -> localhost/main/list/detail

带有/ 的路线是一条绝对路线,意味着您想去那里。

localhost/main -> 路由到/list -> localhost/list -> 路由到/detail -> localhost/detail。

如果您在列表页面上,您可以路由到detail,但如果您在主页上并且想要查看详细信息,则必须使用/main/list/detaillist/detail

【讨论】:

    【解决方案2】:

    尝试在路由前添加“/”

    &lt;a [routerLink]="['/restaurantdetail', restaurant.id]"&gt;{{restaurant.name}}&lt;/a&gt;

    【讨论】:

    • 哇,花了很长时间试图追踪这个,真的很感激它的工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-06
    • 2017-11-10
    • 2019-01-20
    • 2021-04-25
    • 2020-12-06
    相关资源
    最近更新 更多