简体   繁体   中英

Angular 5 Routing issue on child route

I have a routed in angular application called User, then i have a child route called UserDetails, when i click edit i would like to navigate to a new route (userdetails), i'm getting an error Cannot match any routes. URL Segment: 'user/1'. Below is my routing configurations

Excepted result http://localhost:4200/user - Grid page http://localhost:4200/user/1 - Edit page

app.routing.ts

export const routes: Routes = [
  {
    path: '',
    redirectTo: 'dashboard',
    pathMatch: 'full',
  },
  {
    path: '',
    component: FullLayoutComponent,
    data: {
      title: 'Home'
    },
    children: [
      {
        path: 'dashboard',
        loadChildren: './views/dashboard/dashboard.module#DashboardModule'
      },
      {
        path: 'user',
        loadChildren: './views/user/user.module#UserModule',
      } 
    ]
  },
  {
    path: 'login',
    component: SimpleLayoutComponent,
    data: {
      title: ''
    },
    children: [
      {
        path: '',
        loadChildren: './views/login/login.module#LoginModule',
      }
    ]
  }
];

user-routing.module.ts

const routes: Routes = [
  {
    path: '',
    component: UserComponent,
    data: {
      title: 'User'
    },
    children: [
      {
        path: 'user/:id',
        component: UserDetailsComponent,
        data: {
          title: 'User Details'
        }
      }
    ]
  }
];

You can make changes to your user-routing.module.ts as follow.

const routes: Routes = [
 {
   path: '',
   component: UserComponent,
   data: {
     title: 'User'
   },
   children: [{
     path: 'User',
     component: UserComponent,
     pathMatch: 'full',
   },{
     path: 'user/:id',
     component: UserDetailsComponent,
     data: {
      title: 'User Details'
    }
  }
  ]
 }

];

When you click on edit, call a function example

import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
constructor(private router: Router,
          private route: ActivatedRoute){
}
editUserData(){
  this.router.navigate([id],{relativeTo: this.route});
  return false;
}

In your user-routing.module.ts, try ":id" instead of "user/:id"

const routes: Routes = [
  {
    path: '',
    component: UserComponent,
    data: {
      title: 'User'
    },
    children: [
      {
        path: ':id',
        component: UserDetailsComponent,
        data: {
          title: 'User Details'
        }
      }
    ]
  }
];

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