【问题标题】:Redirection to parent route instead of child on page refresh页面刷新时重定向到父路由而不是子路由
【发布时间】:2020-06-15 19:31:21
【问题描述】:
{
        path: '',
        component: componentA,
        children: [
            {
                path: '',
                component: componentB,
                pathMatch: 'full'
            },
            {
                path: 'upload',
                component: UploadComponent,
                children: [
                    {
                        path: 'step_1',
                        component: StepOneComponent,
                        pathMatch: 'full'
                    },
                    {
                        path: 'step_2',
                        component: StepTwoComponent,
                        pathMatch: 'full'
                    },
                    ...

当前行为:

UploadComponentngOnInit() 中,我这样做:

ngOnInit() {
        this.router.navigateTo(['step_1']);
}

如果您在StepTwoComponent 上并刷新页面,您将被重定向到StepOneComponent

我认为发生这种情况是因为首先正在加载 UploadComponent,它重定向到 StepOneComponent 而不是当前。

UploadComponent.html 包括:

<div>
       <!-- some content -->
</div>

<div>
       <!-- some content -->

       <router-outlet></router-outlet>

       <!-- some content -->
</div>

问题:

如何刷新不重定向到StepOneComponent,但重定向到当前?

【问题讨论】:

  • 您可以将实际路线存储在localStorage中,例如。 localStorage.setItem('route', 'step_2');然后在 ngOnInit() 中获取这条路线并导航

标签: angular typescript routes angular-routing


【解决方案1】:

在孩子中注册路线''(未满)和'**'(通配符路线),以便他们导航到step_1



{
        path: '',
        component: componentA,
        children: [
            {
                path: '',
                component: componentB,
                pathMatch: 'full'
            },
            {
                path: 'upload',
                component: UploadComponent,
                children: [
                    {
                        path: 'step_1',
                        component: StepOneComponent,
                        pathMatch: 'full'
                    },
                    {
                        path: 'step_2',
                        component: StepTwoComponent,
                        pathMatch: 'full'
                    },
                    // put these 2 new routes at the end
                    {
                     path: '',
                     redirectTo: 'step_1',
                     pathMatch: 'full',
                    },
                    {
                     path: '**',
                     redirectTo: 'step_1',
                     pathMatch: 'full',
                    }....

UploadComponentngOnInit 中,删除导航到'step_1' 的逻辑。

现在,当您在step_2 上刷新时,您应该留在step_2

【讨论】:

  • 我认为顺序很重要:path: '' 应该放在第一位,通配符放在最后
  • 是的,顺序很重要,将这两条新路线放在底部。
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 2015-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
相关资源
最近更新 更多