David
David

Reputation: 6111

Angular Routing Parameter Routing Incorrectly

I am trying to setup my Angular routing and I do not think that I am doing it correctly. I have the following:

const routes: Routes = [
    {
        path: '',
        children: [
            {
                path: '',
                pathMatch: 'full',
                redirectTo: '/login'
            },
            ... // truncated for brevity
            {
                component: ClientErrorComponent,
                path: 'error'
            },
            {
                path: 'form',
                children: [
                    {
                        component: FormEntriesComponent,
                        path: ':formId',
                        pathMatch: 'full',
                        children: [
                            {
                                component: FormEntryComponent,
                                path: ':id'
                            }
                        ]
                    },
                    {
                        path: '',
                        pathMatch: 'full',
                        redirectTo: '/error?code=400&info=You cannot go to an empty form.'
                    }
                ]
            }
        ]
    },
    {
        path: '**',
        redirectTo: '/error?code=400&info=Uh oh! Something went wrong, you used an invalid URL somehow.'
    }
];

What I would like to do is when I go to localhost:4200/form/1 it goes to the first child child component of form and when I go to localhost:4200/form/1/1 it goes to the first child's child component.

However, every time I try to go to the former it hits ** redirect.

I thought followed the advice of this thread Angular router parameter, but I continue to hit the redirect. What am I doing wrong?

Upvotes: 0

Views: 639

Answers (1)

michal.materowski
michal.materowski

Reputation: 447

You're not getting route match, because you try to implement pathMatch: full strategy.

Router cannot find the route which has explicitly path form/:formId/:id so it ignores it and hits "**" redirect.

Notice that you're getting match for form/:formId because path: 'form' has default pathMatch strategy and it is able to access children segment and look for a :formId match there.

Remove this segment and make sure FormEntriesComponent has <router-outlet></router-outlet> in it's template.

{
    path: 'form',
    children: [
      {
        component: FormEntriesComponent,
        path: ':formId',
        children: [
          {
            component: FormEntryComponent,
            path: ':id',
          },
        ],
      },
    ],
  },

Upvotes: 1

Related Questions