我开始关注ngrx Store,看到使用Angular异步管道的便利性.同时我不确定是否大量使用Angular异步管道是一个不错的选择.
我举一个简单的例子.让我们假设在同一模板中我需要显示从Store检索的对象(例如Person)的不同属性.
一段模板代码可以
<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);
}
.....
.....
}
据我所知,这段代码暗示了3个订阅(通过异步管道在模板中制作)到同一个Observable(person $).
另一种方法是在MyComponent中定义1个属性(person),并且只有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>
现在问题
这两种方法在性能方面有什么不同吗?大量使用异步管道(即大量使用订阅)是否会影响代码的效率?
感谢任何指导
也不应该将应用程序组合为智能和演示组件.
优点:
>智能控制器上的所有buissness逻辑.
>只需一个订阅
>可重用性
>演示控制器只有一个责任,只是提供数据而不知道数据来自何处. (松散耦合)
回答最后一个问题:
大量使用异步管道会影响效率,因为它会订阅每个异步管道.如果您正在调用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
> http://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/