Home > Software design >  Why does my redirect fail to load the expected component?
Why does my redirect fail to load the expected component?

Time:07-13

I have an Angular application with a redirect in place within the routing module to handle old urls, however the redirect is not hitting the expected routes, and instead falls through to the wildcard route. Below is a simplified example of the issue:

const routes: Routes = [
    {
        path: 'old',
        redirectTo: '..'
    },
    {
        path: 'a',
    component: AComponent
    },
    {
        path: 'b',
    component: BComponent
    },
    { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }
];

I'm expecting /old/a to redirect to /a and old/b to redirect to /b. This doesn't happen.

Instead, the URL in the browser URL bar is correctly rewritten, but Angular loads the PageNotFoundComponent. If I then manually refresh the page, the correct component loads.

I've tried enabling route tracing, and the rewrite seems to be applied as expected:

NavigationEnd(id: 1, url: '/old/a', urlAfterRedirects: '/../a')

Why does the redirect not result in the expected components being loaded, and how do I ensure that it will?

Edit: Stackblitz showing the problem: https://stackblitz.com/edit/angular-e1gt7c Navigate to old/a and notice that the URL is correctly rewritten to /a, but the "Page not found" message is shown instead of "A works!"

CodePudding user response:

Use parameters: instead of

    {
        path: 'old',
        redirectTo: '..',
    },

go

    {
        path: 'old/:child',
        redirectTo: ':child',
    },

https://stackblitz.com/edit/angular-e1gt7c-twawde?file=src/app/app-routing.module.ts

  • Related