1
votes

I have just spent a long time debugging an issue I do not understand. Basically every time I clicked on a button or anything with a click event on my page the template of a particular component would re-subscribe to an observable, even when clicking on un-related components on the page.

NB: All my components also use OnPush Change Detection.

In my Angular 9 component I had the following piece of code.

Notice that this is a getter function!

public get riskFactorModel(): Observable<ModelBuilderModel> {
    return this.model('riskFactors').pipe(map(riskFactors => {
      // Do stuff here 
    }));
  }

And in my template I had this

<div *ngIf="(riskFactorModel | async) let _riskFactor">
        <div class="errors" *ngIf="_riskFactor.modelErrors && _riskFactor.modelErrors.length > 0">
          <div *ngFor="let error of _riskFactor.modelErrors">
            {{error.message}}
          </div>
        </div>
      </div>

All I have done is move the observable to a property on my component like so

export class RiskFactorsBuilderComponent extends ComponentBase implements OnInit, OnDestroy {
      
    public riskFactorModel: Observable<ModelBuilderModel>;
    
      constructor() {
        super();
      }
    
      public ngOnInit(): void {
        this.riskFactorModel = this.getRiskFactorModel();
      }
    
      public getRiskFactorModel(): Observable<ModelBuilderModel> {
        return // do getObservable stuff here 
    }
}

And now the constant re-subscription to the observable has stopped?!?! Can someone please explain to me why, this feels like a bug with Angular to me.

Thanks in Advance

1
please make some prototype somewhere which i best way to represent your problem, so that other quickly get into probleum and give solution to you - Jadli
@Jadli Please read my post. I have found the solution I just don't understand it. - Lenny D

1 Answers

0
votes

every time a change detection cycle is run your getter was getting invoked and was providing a new observable you were subscribing too. putting the observable in a property is the only way around it (known to me). P.S. why your change detection was running if you have OnPush strategy is another question. And getter is still a function that gets called, it's now the same as property