David Kassa
David Kassa

Reputation: 754

Angular2 bind observable function instead of property

I'm confused about something, which I assume is fundamental about reactive programming, so I'm looking for some clarification.

Why does example #1 work, but example #2 fail horribly?

Example #1:

Component

export class AppComponent {
  weeklyCount: Observable<number>[];

  constructor(private service: MyService) {
    this.weeklyCount = [service.getCountByDay("12/18/2016"),service.getCountByDay("12/28/2016")];
  }

Template

<ul>
  <li class="text" *ngFor="let count of weeklyCount ">
    {{ count | async }}
  </li>
</ul>

Example #2

Component

export class AppComponent {

  constructor(private service: MyService) {
  }

  thisWeeksCount(): Observable<number>[] {
    var a =  this.service.getCountByDay("12/18/2016"); 
    var b =  this.service.getCountByDay("12/28/2016"); 
    return [a,b];
  }

Template

<ul>
  <li class="text" *ngFor="let count of thisWeeksCount()">
    {{ count | async }}
  </li>
</ul>

I'm using AngularFire2 under the covers of the service, but the service is returning rxjs Observables.

Edit: "fail horribly" = page doesn't return results, becomes unresponsive until killed, and memory keeps growing. This makes sense based on the accepted answer.

Upvotes: 1

Views: 478

Answers (1)

martin
martin

Reputation: 96891

I don't know what you mean by "fail horribly" but these two aren't the same:

  1. Creates an array with two Observables that is later iterated in your template.

  2. Creates a new array with Observables every time the change detection needs to check whether this expression has changed. This means thisWeeksCount() method is going to be called extremely often creating a lot of Observables and probably a lot of requests to your AngularFire2 database.

So you probably want to use the first option.

Upvotes: 3

Related Questions