After facing a puzzling debugging session, I finally figured out an issue that had me scratching my head. Every time I clicked on a button or any element with a click event on my page, the template of a specific component would re-subscribe to an observable, even when interacting with unrelated components.
It's important to note that all my components utilize OnPush Change Detection.
In my Angular 9 component, I stumbled upon the following code snippet.
This is crucial - it's a getter
function!
public get riskFactorModel(): Observable<ModelBuilderModel> {
return this.model('riskFactors').pipe(map(riskFactors => {
// Do stuff here
}));
}
Furthermore, in my template, the code looked like 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>
To solve the constant re-subscription issue, I simply moved the observable to a property within my component:
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
}
}
Surprisingly, by making this adjustment, the incessant re-subscription to the observable ceased. Can anyone shed some light on why this change resolved the issue? It almost feels like a bug with Angular to me.
Appreciate any insights in advance.