【问题标题】:go back using routerLink使用 routerLink 返回
【发布时间】:2018-07-11 14:47:57
【问题描述】:

我正在使用 routerLink 返回我的页面。

当前路线可以有 3 个级别:

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

另外,我有一些不同的组件,所以它不会总是父母,它可以是父母1,也可以是父母2,也适用于子孙,例如:

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

但点击后退按钮失败

【问题讨论】:

标签: angular angular5 angular-routerlink


【解决方案1】:

如果您尝试“向上​​”导航一级,那您几乎是正确的。

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

这将导航

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

但是,如果您想真正像浏览器的后退按钮一样导航“返回”,则需要使用 javascript。

这个问题有多种现有答案on this StackOverflow question


对于更复杂的事情,这将取决于您正在尝试做什么 - 但它可能需要点击处理程序和一些 URL 的手动操作。

【讨论】:

  • 谢谢,我需要“向上”,我试过这个,但同样的结果,它转到主页而不是父页面。
  • @cucuru 在这种情况下,我怀疑您正在退回到应用程序的“默认路由”,就好像您的 URL 无效一样。如果没有看到您正在使用的特定 URL,很难说,但我建议您尝试(在新选项卡或窗口中)直接导航到“向上”的路线。
  • 谢谢,这是我的第一选择,尝试从 url "/child" 手动删除,它可以工作
  • 您无需手动操作,问题似乎出在您的路由器定义中,否则您的&lt;button [routerLink]="['../'']"&gt; back&lt;/button&gt; 应该可以工作。
  • 我的意思是在浏览器中检查路由器文件是否正确。我在原帖中分享了我的路由配置
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    当它是一个延迟加载的模块时,这是特别观察到的,它 a known bug

    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'} 以获取您当前面临的行为。

    【讨论】:

      【解决方案4】:

      如果你在http://localhost:4200/users/list 并想返回一条路径 使用:../ 将返回一个路径。

      <a  routerLink="../{{user.id}}/edit">Update</a>
      
      

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

      【讨论】:

        猜你喜欢
        • 2020-06-15
        • 2017-04-20
        • 1970-01-01
        • 2017-05-13
        • 1970-01-01
        • 2017-09-26
        • 1970-01-01
        • 2019-11-02
        • 1970-01-01
        相关资源
        最近更新 更多