Angular routerLink和Router.Navigate的行为方式不同

时间:2018-02-07 16:34:29

标签: angular angular5

我在App Routing Module中有如下代码。

const routes: Routes = [
    { path: '', redirectTo:'Person/AllPersons', pathMatch:'full'  },
    { path: 'Person/AllPersons', component: AllPersonsComponent },
    { path: 'Person/AddPerson', component: AddPersonComponent },
    { path: 'Teacher/AllTeachers', component: AllTeachersComponent },
    { path: 'Teacher/AddTeacher', component: AddTeacherComponent }

];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

现在在AllPersonsComponent.html中,我有以下代码。

<a routerLink="Teacher/AddTeacher">Add Teacher</a>

现在我点击它。它不会重定向到AddTeacher组件。相反,它填充错误如下 无法匹配任何路线。网址细分:'人/ AllPersons /教师/ AddTeacher'。

但是当我这样做时,它会重定向到正确的路径。

<a (click)="Func()">Add Teacher</a>

在.ts文件中如下。

Func() {
    this.router.navigate(['Teacher/AddTeacher']);
  }

然后导航到Add Teacher组件。任何人都可以帮我解决为什么routerLink失败以及如何通过routerLink实现它?

3 个答案:

答案 0 :(得分:1)

您的routerLink应该以forwardslash开头 (加上老师)

根据角度文件

如果第一个段以/开头,路由器将从应用程序的根目录中查找路径。

所以如果你在开头添加(/),你的链接将在你的 - domain / Teacher / AddTeacher

开始后呈现

https://angular.io/api/router/RouterLink

答案 1 :(得分:0)

试试这个?

<a [routerLink]="['/Teacher/AddTeacher']">Add Teacher</a>

答案 2 :(得分:0)

我发现您以错误的方式声明了路由,首先应该为PersonTeacher分配2条分离的路由,以及与PersonTeacher相关的其他路由应该是子路由,这里还有一个错误,您应该以小写形式声明所有路由,因此问题的解决方案应如下所示:

const routes: Routes = [
    { path: '', redirectTo:'person/all-person', pathMatch:'full'  },
    { path: 'person', component: PersonComponent,
        children: [
          { path: '', redirectTo: 'overview', pathMatch: 'full' },
          { path: 'all-persons', component: AllPersonComponent},
          { path: 'add-person', component: AddPersonComponent}
        ]
    },
    { path: 'teacher', component: PersonComponent,
        children: [
          { path: '', redirectTo: 'overview', pathMatch: 'full' },
          { path: 'all-teachers', component: AllTeacherComponent},
          { path: 'add-teacher', component: AddTeacherComponent}
        ]
    },

  }

];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})

或者您可以有一条简单的路线personperson/:page-type,并且为此可以有一个组成部分,而在ngOnInit中,您可以拥有类似的路线

showAllPersonTemplate = false;
showAddPersonTemplate = false;

ngOnInit(){
 const pageType = this.router.params
  let pageType = this.route.snapshot.paramMap.get('page-type'); 

  // and here you verify what route user navigate
  if(pageType === 'add-person' ) {
   this.showAddPersonTemplate  = true;
  }

  if(pageType === 'all-person' ) {
   this.showAllPersonTemplate = true;
  }

  // And based on routes params you show or hide different html
}

阅读有关角度文档https://angular.io/guide/router

的更多信息
相关问题