简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM