Angular4:如何绑定到功能导致ngFor

时间:2021-09-05 20:19:33

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. I want ngFor to bind to the result of get_data_observable(loc, day) rather than the expression. Then it would be subscribing to one observable that doesn't change.

我相信在每次对大多数ngFor进行角度检查时都会产生一个新的可观测值,从而导致大量的性能问题。我希望ngFor绑定到get_data_observable(loc, day)的结果,而不是表达式。然后,它将订阅一个不会改变的可观测值。

What's the best way around this?

最好的解决办法是什么?

1 个解决方案

#1


0  

I solved this by enclosing the in-most ngFor in a component, and giving it the functions arguments as its input. Since the arguments themselves never change (per iteration) then only one observable is created for each in-most item.

我通过在组件中封装最内部的ngFor来解决这个问题,并将函数参数作为它的输入。由于参数本身从不更改(每次迭代),因此只为每个in-most项创建一个可观察值。

<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)
    }
}

#1


0  

I solved this by enclosing the in-most ngFor in a component, and giving it the functions arguments as its input. Since the arguments themselves never change (per iteration) then only one observable is created for each in-most item.

我通过在组件中封装最内部的ngFor来解决这个问题,并将函数参数作为它的输入。由于参数本身从不更改(每次迭代),因此只为每个in-most项创建一个可观察值。

<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)
    }
}