简体   繁体   中英

Angular routing not working, it redirects me to the base url

I am trying to use angular router to navigate from my page.

I have a button on click of which I am navigating to some other page.

My current url is: http://localhost:4200/user/12345567 . From here I click on button to navigate away

Here is my button code:

leaveArea(){
    this.router.navigate([ 'account', 'dashboard'], {relativeTo: this.route});
}

I want to navigate to http://localhost:4200/account/dashboard on click.

But instead I get navigated to http://localhost:4200 . For an instant (maybe a milli-second or even less), I do see the url as http://localhost:4200/account/dashboard before it navigates to http://localhost:4200 . Is there something wrong with the routing logic?

Edit

I am adding the routeTrace results:

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

Edit

Here is my routing file:

const appRoutes: Routes = [

    { path: "", component: HomeComponent },


    { path: "account/dashboard", component: AccountDashboardComponent},

    {
         path: "user/:id", component: UserComponent
    }
];

@NgModule({
    imports: [RouterModule.forRoot(appRoutes, { enableTracing: true })],
    exports: [RouterModule]
})
export class AppRoutingModule {}

Simply try using router.navigateByUrl like this -

leaveArea(){
    this.router.navigateByUrl('/account/dashboard');
}

PS: By appending / in the start of the string will consider routing from root level.

You have the blank route first .

It needs to be last .

The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. ( https://angular.io/guide/router )

So...

const appRoutes: Routes = [

    { path: "account/dashboard", component: AccountDashboardComponent},

    { path: "user/:id", component: UserComponent},

    { path: "", component: HomeComponent}
];

Please try and change your routes to

const appRoutes: Routes = [
    { path: "", redirectTo: "home", pathMatch: "full" }
    { path: "home", component: HomeComponent },
    { path: "account/dashboard", component: AccountDashboardComponent},
    { path: "user/:id", component: UserComponent }
];

And change your navigation line to

this.router.navigate(['/account', 'dashboard']);

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