【问题标题】:Separate routing logic from component logic in Angular在 Angular 中将路由逻辑与组件逻辑分开
【发布时间】: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


【解决方案1】:

你可以通过两种方式做到这一点。

1.使用resolvers

你可以在路由中附加一个解析器

{
    path: 'hero/:id',
    component: HeroDetailComponent,
    resolve: {
        hero: HeroDetailResolver
    }
}

HeroDetailResolver 将包含从服务器获取英雄详细信息的所有逻辑。在component 中,您可以捕获解析器数据。

this.route.data.subscribe(data => {
    this.hero = data.hero;
});

如果您不熟悉angular resolvers,它们是一个方便的工具,可以在component 加载之前预取一些服务器数据。

2。使用smart parentdumb child 组件

使用smart parent component 获取所有服务器数据并将它们提供给dumb child components。在这种情况下,您可以使用HeroDetailLayoutComponent 来获取英雄详细信息。然后将其作为@Input() 传递给HeroDetailComponent

// in app-routing.module.ts
{ path: 'hero/:id': component: HeroDetailLayoutComponent }

// in hero-detail-layout.component.ts
constructor(private route: ActivatedRoute, private heroService: HeroService) {}

ngOnInit() {
    const id = +this.route.snapshot.paramMap.get('id');
    this.heroService.getHero(id).subscribe(hero => this.hero = hero);
}

// hero-detail-layout.component.html
<hero-detail [hero]='hero'></hero-detail>

// in hero-detail.component.ts
@Input() hero: any[];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-13
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-18
    • 2013-12-15
    • 1970-01-01
    相关资源
    最近更新 更多