Updating Angular 9 template to resubscribe to Observable upon mouse click in getter function

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.

Answer №1

Whenever a change detection cycle runs, your getter gets called and returns a new observable that you subscribe to. Storing the observable in a property seems to be the only workaround that I know of. P.S. It's curious why your change detection is triggered when using the OnPush strategy. Also, keep in mind that a getter still functions as a callable property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The VueJS function is not defined

Looking for a way to fetch data from graphql in my vue project and store it in a variable. The function is asynchronous and the value of rawID needs to be awaited. However, there is a possibility that it could result in undefined, causing an error in the ...

Angular: No routes found that match the URL segment

I encountered an issue with my routes module where I am receiving the error message Cannot match any routes. URL Segment: 'edit-fighter' when attempting to navigate using the <a> link. The only route that seems to work is the champions-list ...

Using Pydantic to define models with both fixed and additional fields based on a Dict[str, OtherModel], mirroring the TypeScript [key: string] approach

Referencing a similar question, the objective is to construct a TypeScript interface that resembles the following: interface ExpandedModel { fixed: number; [key: string]: OtherModel; } However, it is necessary to validate the OtherModel, so using the ...

Service injection results in an error

I am encountering an issue while trying to inject a service into a component, and the error message I receive is as follows: EXCEPTION: TypeError: Cannot read property 'getDemoString' of undefined It appears that the service is not being prop ...

The higher-level modules in Angular 2 are having trouble locating their declarations

I have a cascading module structure, categorized by different features: /app /lib (not considered a module) /pipes capitalize.pipe.ts /portal /dashboard /public Each module is designed to be lazily loaded with their own routes. Below ...

What is the role of authguard in securing routes?

When developing an application, I encountered the need to implement authorization to protect routes using AuthGuard. However, I now face the challenge of securing child routes based on a role system obtained from the backend during login. For example, if t ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Is it possible to import a custom module after an Angular 2 app has been bootstrapped?

I'm currently in the process of developing a business web application using Angular2 that is based on a web API. But I've encountered a challenge. My goal is to bootstrap my Angular2 app using AuthModule, which is a custom module I have created. ...

Specialized purpose for typed arrays

Given an array containing elements of two different entities: interface A { type: string } interface B { type: number } const a = {} as A const b = {} as B const array = [a, b] The array is of type (A | B)[] How can we create a utility type that ...

Refresh the information being received without initiating a new process

I am fetching data from an ngrx/store I have subscribed to the data this.store.select(somedataList) .subscribe(myList => { myList.propertyA = "a different value"; }); After modifying the property values upon subscription, I must update the data ...

Angular Pipe Date Error: "Timestamp conversion failed"

Having an issue with using a pipe in Angular, specifically when using {{fechaCreacion | date: 'medium'}}. The error I'm encountering is: Unable to convert Timestamp (seconds = 1528157765, nanoseconds = 878000000)" into a date 'for pipe& ...

The "library" is encountering errors due to missing dependencies, specifically @angular/material/form-field

I've been working with a shared component library project that has been running smoothly for a while now. Recently, I decided to replace some of the custom components with Angular Material components. However, after adding NgMat to the library project ...

Altering the parent component's output depending on a boolean value established in the child component within Angular

Recently I began learning Angular and find myself in need of some assistance when it comes to managing a specific situation with Angular 16. In our project, we have two different versions of the site header represented by two components - one as the defaul ...

Guide to choosing a default setting in an ng2 framework by utilizing a child component

Currently, I am in the process of developing an application where I have created an input component that can adapt to various types such as text input, select, text area, and more. To achieve this flexibility, I set up a model to provide all necessary inf ...

The function encounters an undefined array when called, despite the array being defined outside of the

Encountering an issue where an array I initiate is suddenly undefined within a function. Here is the code snippet: import { Component, OnInit } from '@angular/core'; import { text } from '@angular/core/src/render3'; import{SheetModel} ...

TypeScript in conjunction with Eslint is throwing an error stating it is unable to locate a particular

One of the modules is causing eslint complaints, even though it is installed and functioning properly in the code. Error message: Unable to resolve path to module '@azure/functions'.eslintimport/no-unresolved az/index.ts import { AzureFunction ...

It seems like there is an issue with your network connection. Please try again

Recently, I made the switch to EndeavourOS, which is based on Archlinux. I completed all my installations without any issues and attempted to create a new NestJs project after installing NVM, Node's latest version, and the NestJs/cli. However, when I ...

When the input type is set to 'number', FormGroup.valueChanges will only trigger on 'change' and 'blur' events

Issue: To replicate the problem, visit this Stackblitz link: https://stackblitz.com/edit/angular-feu1az The event handler is behaving unexpectedly when the value of the last field (of type number) is changed. Unlike Text 1 and Text 2 fields where the eve ...

Issue with vue-class-component: encountering TS2339 error when trying to call a method within

My vuejs application is being built using vue-cli-service. After a successful build, I encountered TS2339 errors in my webstorm IDE: Test.vue: <template> <div>{{method()}}</div> </template> <script lang="ts"> impor ...

The element's type is implicitly set to 'any' as the expression of type 'string' is unable to index the 'PointDto' type

Comparing the values of x1, y1 and z1 in PointDto objects (point1 and point2) Example :- point1 => PointDto: { x1: "1.000000", y1: "1.0", z1: undefined pointIndex: 0, } point2 =& ...