【发布时间】:2019-09-09 08:26:44
【问题描述】:
我正在尝试学习 Angular,但我在路由方面遇到了关注点分离问题。在我发现的所有指南中,发生的情况是您在路由模块中指定路由和参数,但在组件文件中解析它们。例如,在经典的英雄之旅示例中:
// in app-routing.module.ts
{ path: 'hero/:id': component: HeroDetailComponent }
// in hero-detail.component.ts
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
但在本教程的前面,您所拥有的是 Hero 对象被用作 Input():
@Input() hero: Hero;
你会绑定到它:
<hero-detail [hero]='hero'></hero-detail>
我想要的是能够保留该逻辑,而是解析 URL 并将 Input()s 传递到与路由模块相同的文件中,并保持组件文件原样。比如:
// app-routing.module.ts
{
path: 'hero/:id', component: HeroDetailComponent, inputs: path => ({ hero: getHeroObject(+path.params["id"]) })
}
Angular 路由中是否有任何选项可以执行此类操作?如果没有,你能想出一种迂回的方式来分离逻辑部分吗?我想到的一件事是在路由模块中为每个路径创建单独的组件,每个组件都呈现“纯逻辑”组件,例如:
// app-routing/hero-detail-route.component.ts
constructor(
private route: ActivatedRoute,
private heroService: HeroService,
private location: Location
) {}
ngOnInit() {
const id = +this.route.snapshot.paramMap.get('id');
this.heroService.getHero(id)
.subscribe(hero => this.hero = hero);
}
<!--- app-routing/hero-detail-route.component.html -->
<hero-detail [hero]='hero'></hero-detail>
但这只是“解决问题”,不是吗?
有什么想法吗?
提前致谢!
【问题讨论】:
-
您找到更好的解决方案了吗?
标签: angular routing angular-routing