Angular2學習之懶載入(Lazy)路由(router)問題
阿新 • • 發佈:2019-02-15
路由是Angular2中經常用到的.而且在Angular2中添加了懶載入(lazy).
問題描述:
上面為檔案目錄.具體是在hero-routing.module.ts將上面三個資料夾中各元件繫結. 繫結程式碼:
介面:import {RouterModule} from "@angular/router"; import {NgModule} from "@angular/core"; import {DashboardComponent} from "./dashboard/dashboard.component"; import {HeroesComponent} from "./heroes/heroes.component"; import {HeroDetailComponent} from "./hero-detail/hero-detail.component"; import {HeroSearchComponent} from "./hero-search/hero-search.component"; @NgModule({ imports: [RouterModule.forChild([ { path: '', component: HeroSearchComponent, children: [ { path: 'dashboard', component: DashboardComponent }, { path: 'heroes', component: HeroesComponent }, { path: 'detail/:id', component: HeroDetailComponent }, ] } ])], exports: [RouterModule] }) export class HeroRoutingModule {}
點選以上item跳轉到detail詳情中。
在此問題出現了
找不到路由。
解決方法:
1、修改跳轉事件
constructor(
private router: Router,
private route: ActivatedRoute,
private heroService: HeroService) { }
新增ActivateRoute匯入this.router.navigate(['../detail', this.selectedHero.id],{relativeTo: this.route});
其中relativeTo是相對路徑,因為hero-routing.module.ts檔案沒和“跳轉路由”在相同資料夾下,所以使用相對路徑來尋找。若不新增
則在根目錄中的路由中尋找{relativeTo: this.route}
2、介面路徑修改
<a class="button" routerLink="{{'../detail/'+selectedHero.id}}" routerLinkActive="active">檢視詳請</a>
到此問題解決