我开始查看 ngrx Store,并看到使用 Angular 异步管道的便利性。同时我不确定大量使用 Angular 异步管道是否是一个不错的选择。
我举一个简单的例子。假设在同一个模板中,我需要显示从商店检索的对象(例如人员)的不同属性。
一段模板代码可以是
<div>{{(person$ | async).name}}</div>
<div>{{(person$ | async).address}}</div>
<div>{{(person$ | async).age}}</div>
而组件类构造函数将具有
export class MyComponent {
person$: Observable<Person>;
constructor(
private store: Store<ApplicationState>
) {
this.person$ = this.store.select(stateToCurrentPersonSelector);
}
.....
.....
}
据我了解,这段代码意味着对同一个 Observable 的 3 个订阅(通过异步管道在模板中进行)(person$
).
另一种方法是定义 1 个属性 (person
)在 MyComponent 中并且只有 1 个订阅(在构造函数中)来填充该属性,例如
export class MyComponent {
person: Person;
constructor(
private store: Store<ApplicationState>
) {
this.store.select(stateToCurrentPersonSelector)
.subscribe(person => this.person = person);
}
.....
.....
}
而模板使用标准属性绑定(即没有异步管道),例如
<div>{{person.name}}</div>
<div>{{person.address}}</div>
<div>{{person.age}}</div>
现在问题
这两种方法在性能方面有什么区别吗?大量使用异步管道(即大量使用订阅)是否会影响代码的效率?
两者都不应该将您的应用程序编写为智能组件和演示组件。
优点:
- 所有业务逻辑都在智能控制器上。
- 只需订阅一个
- 可重复使用性
- 呈现控制器只有一个职责,只呈现数据,并不知道数据从哪里来。 (松散耦合)
回答最后一个问题:
大量使用异步管道会影响效率,因为它会订阅每个异步管道。如果您调用 http 服务,您会更注意到这一点,因为它将调用每个异步管道的 http 请求。
智能组件
@Component({
selector: 'app-my',
template: `
<app-person [person]="person$ | async"></app-person>
`,
styleUrls: ['./my.component.css']
})
export class MyComponent implements OnInit {
person$: Observable<Person>;
constructor(private store: Store<ApplicationState>) {}
ngOnInit() {
this.person$ = this.store.select(stateToCurrentPersonSelector);
}
}
演示组件
@Component({
selector: 'app-person',
template: `
<div>{{person.name}}</div>
<div>{{person.address}}</div>
<div>{{person.age}}</div>
`,
styleUrls: ['./my.component.css']
})
export class PersonComponent implements OnInit {
@Input() person: Person;
constructor() {}
ngOnInit() {
}
}
欲了解更多信息,请检查:
- https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u27zmzf25 https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0#.u27zmzf25
- http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/ http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)