通过routerLink返回上一页

12

我正在使用routerLink返回页面。

当前路由可能有3个级别:

myurl.com/parent
myurl.com/parent/child
myurl.com/parent/child/grandchild

另外,我有一些不同的组件,所以它不总是父级,它可以是parent1或parent2,对于child和grandchild也是如此。例如:

myurl.com/parent2/child1/grandchild2

我想要的是始终返回到上一个级别,例如:

myurl.com/parent/child/grandchild -> myurl.com/parent/grandchild

我所做的是:

<button [routerLink]="['../'']">
       back
</button>

但它总是导航到“myurl.com”

我该如何解决?

正如一些用户建议的那样,我正在分享我的路由配置:

在app.routing.ts中:

const APP_ROUTES: Routes = [
{
  path: '',
  canActivate: [LoggedInGuard],
  children: [
    {path: '', redirectTo: '/mainPage', pathMatch: 'full'},
    {path: 'parent', loadChildren: 'app/parent/parend.module#ParentModule'
]},
{path: '**', redirectTo: ''}
];
在 parent.routing.ts 文件中:
const PARENT_ROUTES: Routes = [
 {path: '', component: ParentComponent},
 {path: ':id', component: ChildComponent},
];

如果在浏览器中我写下:

myurl.com/parent -> it works

但是点击返回按钮失败了


也许这会对你有所帮助:https://dev59.com/2FoU5IYBdhLWcg3wsoZ8 - Silvester Schn.
谢谢,我已经阅读了这个,但没有帮助到我 :( - cucuru
你能分享一下你的路由配置吗? - eduPeeth
4个回答

26

如果你试图向"上"导航到上一级,那么你几乎是正确的。

<a routerLink="..">Up</a>

这将导航

myurl.com/parent/child/grandchild -> myurl.com/parent/child

然而,如果你想像浏览器的后退按钮一样真正地导航“回退”,你需要使用JavaScript。

对于这个问题,有许多现有的答案可以在这个 StackOverflow 问题中找到。


对于任何更复杂的情况,它将取决于你所尝试完成的具体任务 - 但它可能需要一个点击事件处理程序和对URL的一些手动操作。


1
谢谢,我需要往“上”走。我尝试了这个,但是结果一样,它跳转到主页面而不是父级页面。<button mat-icon-button routerLink=".."> 返回 </button> - cucuru
@cucuru 如果是这样的话,我怀疑你正在回退到应用程序的“默认路由”,就好像你有一个无效的URL一样。如果没有看到你使用的具体URL,很难说,但我建议你尝试直接导航(在新标签页或窗口中)到“上升”的路线。 - Vlad274
谢谢,那是我的第一选择,我尝试手动从URL中删除“/child”,并且它起作用了。 - cucuru
你不需要手动操作,问题似乎出在你的路由定义上,否则你的 <button [routerLink]="['../'']">返回</button> 应该可以工作。 - eduPeeth
我的意思是在浏览器中检查路由文件是否正确。我会在原始帖子中分享我的路由配置。 - cucuru

2
尝试这个:[routerLink]="['../child']"

1
这种情况通常出现在延迟加载模块时,而且这曾经是一个已知的错误Angular 11:它可以直接使用,效果良好。
@NgModule({
  imports: [RouterModule.forRoot(routes, {})], // relativeLinkResolution === 'corrected' by default
  exports: [RouterModule],
})
export class AppRoutingModule {}
Angular 11之前:显式使用{relativeLinkResolution: 'corrected'}
@NgModule({
  imports: [RouterModule.forRoot(routes, {relativeLinkResolution:'corrected'})],
  exports: [RouterModule],
})
export class AppRoutingModule {}

你也可以设置{relativeLinkResolution:'legacy'}以获得当前所面临的行为。

0
如果您在 http://localhost:4200/users/list 中,并想返回一个路径,请使用 ../,它将返回一个路径。
<a  routerLink="../{{user.id}}/edit">Update</a>

结果:http://localhost:4200/users/2/edit


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接