ngIf - loading duplicates on observable with ngFor and async pipe


#1

I’ve created something like a tabs component where i’m loading some content based on the value of the selected tab. However each time I go between the tabs it loads the data from my service again on top of the old data so I get duplicates…

This is in my component:

ngOnInit() {
    if (Meteor.userId()) {
      if (this.myTasksSub) {
        this.myTasksSub.unsubscribe();
      }

      this.myTasksSub = MeteorObservable.subscribe('entities').subscribe(() => {
        MeteorObservable.autorun().subscribe(() => {
          this.myTasks = this._entityService.findMyTasks(this.user);
        });
      });
    }
  }

and I load it in the standard way in my html:

<ul *ngIf="selectedTab==1">
   <li *ngFor="let myTask of myTasks | async">

what am i doing wrong?


#2

Could it be because the async pipe is run each time the ngIf containing is activated and so it loads the data again?


#3

I managed to fix this by subscribing to the observable directly and avoiding the async pipe. This was a bit of a guess so I would appreciate if anyone could explain why the async pipe was doing that?

This is the working code:

myTasks: Entity[]; // this used to be Observable<Entity[]>;

      this.myTasksSub = MeteorObservable.subscribe('entities').subscribe(() => {
        MeteorObservable.autorun().subscribe(() => {
          this._entityService.findMyTasks(this.user).subscribe(tasks => {
            this.myTasks = tasks;
          });
        });
      });

Then no need for the async pipe with the ngFor