[英]Angular4: How to bind to function result in ngFor
Given this code: 给出以下代码:
<div *ngFor='let loc of user.locations | async'>
<div *ngFor='let day of days'>
<div *ngFor='let data of get_data_observable(loc, day) | async'>
...
</div>
</div>
</div>
This is connecting to a Firebase database. 这正在连接到Firebase数据库。
get_data_observable(loc, day) => this.db.list(`/users/${this.auth.uid}/times/${loc.$key}/${day}`)
I believe a new observable is being created every time Angular checks the in-most ngFor, causing massive performance issues. 我相信,每当Angular检查最里面的ngFor时,都会创建一个新的可观察的对象,这会导致性能问题。 I want ngFor to bind to the result of get_data_observable(loc, day)
rather than the expression. 我希望ngFor绑定到get_data_observable(loc, day)
的结果,而不是表达式。 Then it would be subscribing to one observable that doesn't change. 然后,它将订阅一个不变的可观察对象。
What's the best way around this? 最好的办法是什么?
I solved this by enclosing the in-most ngFor in a component, and giving it the functions arguments as its input. 我通过将最里面的ngFor封装在一个组件中并为其提供函数参数作为输入来解决此问题。 Since the arguments themselves never change (per iteration) then only one observable is created for each in-most item. 由于参数本身从不改变(每次迭代),因此对于每个最里面的项目仅创建一个可观察的对象。
<app-day [loc]='loc' [day]='day'></app-avail-day>
And 和
export class DayComp {
obs
@Input() loc
@Input() day
ngOnChanges(){
this.obs = get_data_observable(this.loc, this.day)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.