NgrxStore和Angular – 大量使用异步管道或在构造函数中只订阅一
我开始关注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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |