简体   繁体   中英

How to change the routerlink in nav bar in Angular 4?

I am having the issue of routing to a incorrect routelink. How to avoid this? sorry for being a noob.

The error I am getting from Chrome console is

ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL 
Segment: 'oadmin/add-new-student/add-new-teacher'
Error: Cannot match any routes. URL Segment: 
'oadmin/add-new-student/add-new-teacher'

HTML code of navigation buttons

<md-toolbar color="primary" class="toolbar-student">  
<span >
    <button md-button [mdMenuTriggerFor]="menu1">Student</button>
    <md-menu #menu1="mdMenu">
      <button md-menu-item [routerLink]="['add-new-student']" >Add New Student</button>
      <button md-menu-item>Item 2</button>
    </md-menu>
  </span>
  <span >
    <button md-button [mdMenuTriggerFor]="menu2">Teacher</button>
    <md-menu #menu2="mdMenu">
      <button md-menu-item [routerLink]="['add-new-teacher']" >Add New Teacher</button>
      <button md-menu-item>Item 2</button>
    </md-menu>
  </span>
</md-toolbar>

My Routes

var routes = [
  {path: '',
  component: StudentComponent},
  {path: 'oadmin',
  component: OAdminComponent},
  {path: 'oadmin/add-new-student',
  component: NewStudentComponent},
  {path: 'oadmin/add-new-teacher',
  component: NewTeacherComponent},
];

Navigation bar is common for both routes. When I click "Add New Teacher" route while being inside of "Add New Student" route, I am getting this error. and vice versa. How to avoid this?

When you are inside the oadmin/add-new-student path and you redirect to add-new-teacher you are being actually redirected to oadmin/add-new-student/add-new-teacher because writing [routerLink]="['add-new-teacher']" just appends /add-new-teacher to the current url. Instead what you want is to redirect to oadmin/add-new-teacher so instead of:

[routerLink]="['add-new-teacher']"

You should use this:

routerLink="/oadmin/add-new-teacher"

And you should also change it for add-new-student as if you visit the add-new-teacher and click on add-new-student link you will have the same error

<button md-menu-item routerLink="/oadmin/add-new-student" >Add New Student</button>

在angular 4中,您需要根据index.html页面上的base href提及完整路径,而不是相对路径

[routerLink]="['/oadmin/add-new-teacher']"

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