简体   繁体   中英

Why does my redirect fail to load the expected component?

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!"

Use parameters: instead of

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

go

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM