Angular2学习之懒加载(Lazy)路由(router)问题

来源:互联网 发布:实现即时通讯的php文件 编辑:程序博客网 时间:2024/06/15 05:47


路由是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>

到此问题解决




参考:[Angular2 Router] Programmatic Router Navigation via the Router API - Relative And Absolute Router Navigation
         
            [Angular2 Router] Optional Route Query Parameters



0 0
原创粉丝点击