简体   繁体   English

Angular2 - 在组件 class 中创建多个变量声明与在模板中直接使用 object

[英]Angular2 - creating multiple variable declarations in component class vs directly using object in template

I have a component which retrieves a large nested object from an http request.我有一个组件从 http 请求中检索大型嵌套 object。 Within my component class, I declare hundreds of variables that extrapolate data from that object and those properties are then interpolated within its template.在我的组件 class 中,我声明了数百个变量,这些变量从 object 中推断出数据,然后将这些属性插入到其模板中。

This has resulted in my component class having hundreds of lines of code simply from those properties being declared and assigned.这导致我的组件 class 具有数百行代码,仅来自声明和分配的这些属性。 Would be better to just use the object itself within the template?在模板中使用 object 本身会更好吗? The following is an example to demonstrate:下面是一个例子来演示:

Let's say I have a really large and nested cuisines object that's coming in from a service.假设我有一个非常大的嵌套美食object 来自服务。 With my current approach, within the component class, I declare variables for the individual properties that I need:使用我目前的方法,在组件 class 中,我为我需要的各个属性声明变量:

let italianBreakfast = cuisine.data.breakfast.italian; let... let... let...

This is then interpolated within the template: <div>{{italianBreakfast}}</div>然后在模板中插入: <div>{{italianBreakfast}}</div>

My revised strategy is to simply use the object in the template:我修改后的策略是在模板中简单地使用 object:

<div>{{cuisine.data.breakfast.italian}}</div>

In doing so, the text between the curly brackets in my templates get larger, but I would gain in that I'm no longer declaring properties to store object values in my component class, which would result in saving hundreds of lines of code.这样做时,我的模板中大括号之间的文本会变大,但我会从中受益,因为我不再声明在我的组件 class 中存储 object 值的属性,这将节省数百行代码。 Which would be better and is there a best practice around this?哪个会更好,是否有最佳实践?

You can create smaller components inside this large component and pass them specific parts of the cuisines object as @Input properties.您可以在这个大组件中创建更小的组件,并将cuisines object 的特定部分作为@Input属性传递给它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM