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