使用参数化路由还是@Input()
更好?
我有一个接受id的RecipeList子组件,它有一个参数化的路由,所以这是获取id的一种方法。但是,由于它是子组件,我知道父组件也可以将其作为@Input()
属性传递给子组件。
两者中哪一个更可取,性能更高效?
在以下场景中,我认为@Input()
更有效:
- RecipeListComponent(父组件(
- RecipeComponent(子组件(
- RecipeService
使用@Input((属性
RecipeListComponent(父级(:
recipes: Recipe[];
constructor(private recipeService: RecipeService)
ngOnInit() {
this.recipes = this.recipeService.getRecipes();
}
RecipeListComponent的模板(父模板(:
<!-- Passing recipe element to child's @Input() -->
<app-recipe *ngFor="let recipe of recipes" [routerLink]="[recipe.Id]" [recipe]="recipe"></app-recipe>
配方组件(子(:
@Input() recipe: Recipe;
ngOnInit() {
}
vs
参数化路线+服务
配方组件(子(:
recipe: Recipe;
constructor(private route: ActivatedRoute, private recipeService: RecipeService)
ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.recipe = this.recipeService.getRecipe(+params['id']);
})
}
RecipeListComponent的模板(父模板(:
<!-- We don't pass a property to the child anymore -->
<app-recipe *ngFor="let recipe of recipes" [routerLink]="[recipe.Id]"></app-recipe>
RecipeListComponent(父级(:
recipes: Recipe[];
constructor(private recipeService: RecipeService)
ngOnInit() {
this.recipes = this.recipeService.getRecipes();
}
您应该只发送id、sub-id、页码、页面大小等参数。您应该将这些参数视为刷新后或从书签链接加载页面的基础。
用例:
- 我们应用程序的用户将链接保存在浏览器上,稍后打开
- 用户向另一个用户发送页面url,然后他打开链接
我们应该传递给子组件的所有其他值作为输入。为了扩展这一点,我们的每个模块都将有2种类型的组件,。它们是
- 智能组件(文件夹名称容器(
- Dumb组件(场景名称容器(
智能组件顾名思义,他就是智能组件。他了解模块的业务逻辑。他知道如何与后端或其他服务进行通信以获取信息。他知道如何处理这些信息。
哑组件顾名思义,它们只是演示组件。我们将在这些组件中编写的唯一逻辑将是表示逻辑。这些哑组件将从智能组件接收数据作为输入。这些愚蠢的组件唯一的工作就是显示它们。
哑组件与智能组件之间的通信在某些情况下,哑组件可能需要调用后端服务或获取它们可能显示的新值但是愚蠢的组件从不做业务逻辑。他们只能通过输出将请求传回智能组件
一开始可能会觉得工作量太大。但是,随着我们的应用程序开始增长,管理数据将变得非常困难,并在应用程序中造成不一致。
此方法的优点
- 易于调试
- 组件将更加可重复使用
- 松散耦合的元件